获得领先的空白

Nob*_*ody 2 c# string whitespace .net-4.0

我刚刚编写了这个方法,我想知道框架中是否存在类似的东西?它看起来像是其中一种方法......

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

/// <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);
}
Run Code Online (Sandbox Code Playgroud)

谢谢

编辑: 看完一些评论后,很清楚我还需要处理标签.

我不能给出一个很好的例子,因为网站将空格减少到只有一个,但我会尝试:

假设输入是一个包含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
...
Run Code Online (Sandbox Code Playgroud)

Aus*_*nen 6

我没有运行任何性能测试但是代码更少.

...

whitespace = line.Length - line.TrimStart(' ').Length;

...
Run Code Online (Sandbox Code Playgroud)

  • 注意:您可以删除`''`以获取所有空格而不仅仅是'''`. (3认同)

wag*_*ghe 0

String 上的扩展方法怎么样?我传入了tabLength以使功能更加灵活。我还添加了一个单独的方法来返回空白长度,因为有评论说这就是您正在寻找的内容。

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;
}
Run Code Online (Sandbox Code Playgroud)