获得领先的空白

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

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

///  /// Return the whitespace at the start of a line. ///  /// Round the number of spaces down to the nearest multiple of 4. 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 ... 

String上的扩展方法怎么样? 我通过了tabLength来使function更加灵活。 我还添加了一个单独的方法来返回空白长度,因为一个注释就是你正在寻找的。

 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; } 

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

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

您应该使用Char.IsWhiteSpace而不是与' '进行比较。 并非所有“空间”都是' '

我确信没有任何内置function,但如果您对它们感到满意,可以使用正则表达式来执行此操作。 这匹配行开头的任何空格:

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

注意:这不会像简单的循环一样好。 我会继续你的实施。

什么都没有内置,但如何:

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