我刚刚写了这个方法,我想知道框架中是否已经存在类似的东西?这似乎只是这些方法之一......
如果没有,有更好的方法吗?
/// <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);
}
Thanks
Edit:阅读一些评论后,很明显我还需要处理选项卡。
我无法给出一个很好的例子,因为该网站将空格减少到只有一个,但我会尝试:
假设输入是一个包含 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;
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)