c# - 在 C# 中查找字符串尾随空格数的最佳方法是什么?
问题描述
我假设数百万个带有或不带有尾随空格的字符串。我想计算每个字符串中尾随空格的数量。
我正在为每个字符串执行此操作。
int count = input.Length - input.TrimEnd().Length;
但我认为这是低效的,因为我通过TrimEnd()
为每个字符串使用方法来创建不必要的字符串。
我曾想过使用另一种方法来计算尾随空格,方法是反向遍历每个字符的字符串并检查直到第一个非空格字符(将计数增加 1)。
有没有更快更有效的方法来做到这一点?字符串很小,但有数百万。
解决方案
编辑:我没有进行分析,并将其纳入扩展方法:
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;
}
}
推荐阅读
- javascript - UnhandledPromiseRejectionWarning:错误:协议错误(Runtime.callFunctionOn):目标已关闭。(木偶师)
- python - 在给定条件的情况下填充 numpy 数组中的值
- ruby - 如何模拟sidekiq中的“立即重试”按钮
- python - pyLDAvis:“ValuesView”类型的对象不是 JSON 可序列化的
- c - MIPS GCC 交叉编译器构建失败:“找不到 -lc”
- linux - 每天使用 logrotate 擦除干净的日志文件
- three.js - 是否在内部使用 .matrixWorld?
- json - 无法使用 powershell 更新 json 文件
- c# - 在 c#.net 中将对象序列化为 XmlDocument 后,getelementById 返回 null
- react-native - 命令 npm 运行弹出显示错误弹出失败,退出代码为 1