Hi, 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
...