在 C# 中获取字符串字数的 Surefire 方法是什么
我不知道该怎么做。现在我正在计算空格以获取字符串的字数,但如果有双空格,则字数统计将不准确。有更好的方法吗?
I am not sure how to go about this. Right now I am counting the spaces to get the word count of my string but if there is a double space the word count will be inaccurate. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@Martin v. Löwis 的替代版本,它使用
foreach
和char.IsWhiteSpace()
,在处理其他文化时应该更正确。Alternate Version of @Martin v. Löwis, which uses a
foreach
andchar.IsWhiteSpace()
which should be more correct when dealing with other cultures.虽然基于 Split 的解决方案编写起来很短,但它们可能会变得昂贵,因为所有字符串对象都需要创建然后丢弃。我希望诸如此类的显式算法
更有效(而且它还可以考虑其他空白字符)。
While solutions based on Split are short to write, they might get expensive, as all the string objects need to be created and then thrown away. I would expect that an explicit algorithm such as
is more efficient (plus it can also consider additional whitespace characters).
这似乎对我有用:
This seems to work for me:
尝试 string.Split:
Try string.Split: