代码之家  ›  专栏  ›  技术社区  ›  Nobody

获取前导空格

  •  2
  • Nobody  · 技术社区  · 15 年前

    我刚刚编写了这个方法,我想知道框架中是否已经存在类似的东西?这似乎就是其中一种方法…

    如果没有,有更好的方法吗?

    /// <summary>
    /// Return the whitespace at the start of a line.
    /// </summary>
    /// <param name="trimToLowerTab">Round the number of spaces down to the nearest multiple of 4.</param>
    public string GetLeadingWhitespace(string line, bool trimToLowerTab = true)
    {
        int whitespace = 0;
        foreach (char ch in line)
        {
            if (ch != ' ') break;
            ++whitespace;
        }
    
        if (trimToLowerTab)
            whitespace -= whitespace % 4;
    
        return "".PadLeft(whitespace);
    }
    

    谢谢

    编辑: 在阅读了一些评论之后,很明显我还需要处理标签。

    我不能给出一个很好的例子,因为网站将空间缩小到一个,但我会尝试:

    假设输入是一个带有5个空格的字符串,则该方法将返回一个带有4个空格的字符串。如果输入少于4个空格,则返回 "" . 这可能有助于:

    input spaces | output spaces
    0 | 0
    1 | 0
    2 | 0
    3 | 0
    4 | 4
    5 | 4
    6 | 4
    7 | 4
    8 | 8
    9 | 8
    ...
    
    5 回复  |  直到 15 年前
        1
  •  0
  •   wageoghe    15 年前

    字符串的扩展方法如何?我传递了表的长度以使函数更灵活。我还添加了一个单独的方法来返回空格长度,因为有一个注释是您要查找的。

    public static string GetLeadingWhitespace(this string s, int tabLength = 4, bool trimToLowerTab = true)
    {
      return new string(' ', s.GetLeadingWhitespaceLength());
    }
    
    public static int GetLeadingWhitespaceLength(this string s, int tabLength = 4, bool trimToLowerTab = true)
    {
      if (s.Length < tabLength) return 0;
    
      int whiteSpaceCount = 0;
    
      while (Char.IsWhiteSpace(s[whiteSpaceCount])) whiteSpaceCount++;
    
      if (whiteSpaceCount < tabLength) return 0;
    
      if (trimToLowerTab)
      {
        whiteSpaceCount -= whiteSpaceCount % tabLength;
      }
    
      return whiteSpaceCount;
    }
    
        2
  •  6
  •   Austin Salonen gmlacrosse    15 年前

    我没有运行任何性能测试,但这是更少的代码。

    ...
    
    whitespace = line.Length - line.TrimStart(' ').Length;
    
    ...
    
        3
  •  2
  •   Craig Stuntz    15 年前

    你应该用 Char.IsWhiteSpace 而不是与 ' ' ,通常。并非所有的“空格”都是

        4
  •  2
  •   steinar Justin CI    15 年前

    我确信没有内置的,但是如果您对它们感到满意的话,可以使用正则表达式来实现这一点。这匹配行开头的任何空白:

    public static string GetLeadingWhitespace(string line)
    {
      return Regex.Match(line, @"^([\s]+)").Groups[1].Value;
    }
    

    注意:这样做的效果不如简单的循环好。我会同意你的实现。

        5
  •  0
  •   Kirk Woll    15 年前

    没有内置的,但是如何:

    var result = line.TakeWhile(x => x == ' ');
    if (trimToLowerTab)
        result = result.Skip(result.Count() % 4);
    return new string(result.ToArray());