我不知道该怎么做。现在我正在计算空格以获取字符串的字数,但如果有双空格,则字数将不准确。有一个更好的方法吗?
问问题
480 次
4 回答
4
@Martin v. Löwis 的替代版本,它使用 aforeach
并且char.IsWhiteSpace()
在处理其他文化时应该更正确。
int CountWithForeach(string para)
{
bool inWord = false;
int words = 0;
foreach (char c in para)
{
if (char.IsWhiteSpace(c))
{
if( inWord )
words++;
inWord = false;
continue;
}
inWord = true;
}
if( inWord )
words++;
return words;
}
于 2009-09-02T05:05:13.227 回答
3
虽然基于 Split 的解决方案编写起来很短,但它们可能会变得昂贵,因为所有字符串对象都需要创建然后丢弃。我希望一个明确的算法,如
static int CountWords(string s)
{
int words = 0;
bool inword = false;
for(int i=0; i < s.Length; i++) {
switch(s[i]) {
case ' ':case '\t':case '\r':case '\n':
if(inword)words++;
inword = false;
break;
default:
inword = true;
break;
}
}
if(inword)words++;
return words;
}
效率更高(另外它还可以考虑额外的空白字符)。
于 2009-09-02T04:14:49.773 回答
2
这似乎对我有用:
var input = "This is a test";
var count = input.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length;
于 2009-09-02T03:58:31.957 回答
1
尝试string.Split:
string sentence = "This is a sentence with some spaces.";
string[] words = sentence.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
于 2009-09-02T03:59:12.753 回答