我刚刚写了这个方法,我想知道框架中是否已经存在类似的东西?这似乎只是这些方法之一......
如果不行,有更好的方法吗?
/// <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
...
我没有运行任何性能测试,但这代码较少。
...
whitespace = line.Length - line.TrimStart(' ').Length;
...
我确信没有内置任何内容,但如果您熟悉正则表达式,则可以使用正则表达式来执行此操作。这匹配行开头的任何空格:
public static string GetLeadingWhitespace(string line)
{
return Regex.Match(line, @"^([\s]+)").Groups[1].Value;
}
注意:这不会像简单循环那样执行。我会同意你的实施。
对于任何其他希望将空格作为字符串获取的人,我个人认为这很简单明了:
public static string GetLeadingWhitespace(string str)
{
//Check if str is empty, since String.Replace() throws an exception when the first argument is an empty string
if(str == String.Empty) {
return String.Empty;
}
return str.Replace(str.TrimStart(), "");
}
只需用空字符串替换所有不是前导空格即可。这也适用于任何类型的空白 - 不仅仅是空格。感谢 @bobwki 指出了失败的边缘情况 - 我添加了对空字符串的检查。
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;
}
没有内置任何东西,但是怎么样:
var result = line.TakeWhile(x => x == ' ');
if (trimToLowerTab)
result = result.Skip(result.Count() % 4);
return new string(result.ToArray());
以柯克的答案为基础
var leadingWhiteSpace = line.TakeWhile(x => x == ' ');
leadingWhiteSpace = String.Join("", leadingWhiteSpace.ToArray());