首页 > 解决方案 > 在 C# 中查找字符串尾随空格数的最佳方法是什么?

问题描述

我假设数百万个带有或不带有尾随空格的字符串。我想计算每个字符串中尾随空格的数量。

我正在为每个字符串执行此操作。

int count = input.Length - input.TrimEnd().Length;

但我认为这是低效的,因为我通过TrimEnd()为每个字符串使用方法来创建不必要的字符串。

我曾想过使用另一种方法来计算尾随空格,方法是反向遍历每个字符的字符串并检查直到第一个非空格字符(将计数增加 1)。

有没有更快更有效的方法来做到这一点?字符串很小,但有数百万。

标签: c#

解决方案


编辑:我没有进行分析,并将其纳入扩展方法:

void Main()
{
    string test = "StackOverflow     ";
    int count = test.WhiteSpaceAtEnd();
}

public static class StringExtensions
{
    public static int WhiteSpaceAtEnd(this string self)
    {
        int count = 0;
        int ix = self.Length - 1;
        while (ix >= 0 && char.IsWhiteSpace(self[ix--]))
            ++count;

        return count;
    }
}

推荐阅读