获取前导空白

发布于 2024-09-26 23:27:28 字数 917 浏览 0 评论 0原文

我刚刚写了这个方法,我想知道框架中是否已经存在类似的东西?这似乎只是其中一种方法...

如果没有,是否有更好的方法?

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

谢谢

编辑: 阅读一些评论后,很明显我还需要处理选项卡。

我无法给出一个很好的例子,因为该网站将空格削减为 1 个,但我会尝试:

假设输入是一个包含 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
...

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

北陌 2024-10-03 23:27:28

我没有运行任何性能测试,但这代码较少。

...

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

...

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

...

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

...
无畏 2024-10-03 23:27:28

对于其他希望将空格作为字符串获取的人来说,我个人认为这很简单明了:

    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 指出了失败的边缘情况 - 我添加了对空字符串的检查。

For anyone else looking to get the whitespace as a string, I personally found this to be simple and straightforward:

    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(), "");
    }

Just replace everything that's not the leading whitespace with an empty string. This will also work for any sort of whitespace - not just spaces. Thanks to @bobwki for pointing out an edge case where this failed - I've added a check for empty strings.

江城子 2024-10-03 23:27:28

您应该使用 Char.IsWhiteSpace 而不是与通常是 ' '。并非所有“空格”都是' '

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

冬天的雪花 2024-10-03 23:27:28

我确信没有内置任何内容,但如果您熟悉正则表达式,则可以使用正则表达式来执行此操作。这会匹配行开头的任何空格:

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

注意:这不会像简单循环那样执行。我会同意你的实施。

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.

琉璃梦幻 2024-10-03 23:27:28

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

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;
}
我恋#小黄人 2024-10-03 23:27:28

没有内置任何东西,但是怎么样:

var result = line.TakeWhile(x => x == ' ');
if (trimToLowerTab)
    result = result.Skip(result.Count() % 4);
return new string(result.ToArray());

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());
瘫痪情歌 2024-10-03 23:27:28

以柯克的答案为基础

var leadingWhiteSpace = line.TakeWhile(x => x == ' ');
leadingWhiteSpace = String.Join("", leadingWhiteSpace.ToArray());

Building on Kirk's answer

var leadingWhiteSpace = line.TakeWhile(x => x == ' ');
leadingWhiteSpace = String.Join("", leadingWhiteSpace.ToArray());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文