Get leading whitespace

做~自己de王妃 提交于 2019-12-06 07:50:42

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

I didn't run any performance tests but this is less code.

...

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

...

You should be using Char.IsWhiteSpace instead of comparing with ' ', usually. Not all "spaces" are ' '

I'm sure there's nothing built in, but you can use a regular expression to do this if you're comfortable with them. This matches any whitespace at the beginning of the line:

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

NOTE: This would not perform as well as a simple loop. I would just go with your implementation.

Nothing built in, but how about:

var result = line.TakeWhile(x => x == ' ');
if (trimToLowerTab)
    result = result.Skip(result.Count() % 4);
return new string(result.ToArray());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!