取得领先的空白 [英] Get leading whitespace
问题描述
我刚刚写了这个方法,我想知道,如果类似的东西已经存在于框架?这似乎只是这些方法之一...
如果没有,有没有更好的办法做到这一点?
///<总结>
///返回空格在一行的开始。
///< /总结>
///< PARAM NAME =trimToLowerTab>回合下降到4&LT最近的多个空格的数量; /参数>
公共字符串GetLeadingWhitespace(串线,布尔trimToLowerTab =真)
{
INT空白= 0;
的foreach(在行字符CH)
{
如果(CH =''!)破;
++空白;
}
如果(trimToLowerTab)
空白 - =空白%4;
返回.PadLeft(空白);
}
感谢
编辑: 之后读了一些意见,它清楚,我还需要处理的标签。
我不能给出一个很好的例子,因为该网站修整空间下降到只有一个,但我会尽力:
假设输入是一个字符串,5个空格,该方法将返回一个字符串,用4个空格。如果输入小于4位,它返回,
。
这可能帮助:
输入空间|输出空间
0 | 0
1 | 0
2 | 0
3 | 0
4 | 4
5 | 4
6 | 4
7 | 4
8 | 8
9 | 8
...
关于字符串的扩展方法是什么?我通过在tabLength,使功能更加灵活。我还增加了一个单独的方法返回空白长度因为一个注释,这是你所期待的。
公共静态字符串GetLeadingWhitespace(这个字符串s,诠释tabLength = 4,布尔trimToLowerTab =真)
{
返回新的字符串('',s.GetLeadingWhitespaceLength());
}
公共静态INT GetLeadingWhitespaceLength(这个字符串s,诠释tabLength = 4,布尔trimToLowerTab =真)
{
如果(s.Length< tabLength)返回0;
INT whiteSpaceCount = 0;
而(Char.IsWhiteSpace(S [whiteSpaceCount]))whiteSpaceCount ++;
如果(whiteSpaceCount< tabLength)返回0;
如果(trimToLowerTab)
{
whiteSpaceCount - = whiteSpaceCount%tabLength;
}
返回whiteSpaceCount;
}
I just wrote this method and I'm wondering if something similar already exists in the framework? It just seems like one of those methods...
If not, is there a better way to do it?
/// <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: after reading some comments, Its clear that I also need to handle tabs.
I can't give a very good example because the website trims spaces down to just one but I'll try:
Say the input is a string with 5 spaces, the method will return a string with 4 spaces. If the input is less than 4 spaces, it returns ""
.
This might help:
input spaces | output spaces
0 | 0
1 | 0
2 | 0
3 | 0
4 | 4
5 | 4
6 | 4
7 | 4
8 | 8
9 | 8
...
What about an extension method on String? I passed in the tabLength to make the function more flexible. I also added a separate method to return the whitespace length since one comment that that is what you were looking for.
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;
}
这篇关于取得领先的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!