【发布时间】:2009-09-02 03:54:11
【问题描述】:
我不知道该怎么做。现在我正在计算空格以获取字符串的字数,但如果有双空格,则字数将不准确。有没有更好的方法来做到这一点?
【问题讨论】:
标签: c# regex text-parsing
我不知道该怎么做。现在我正在计算空格以获取字符串的字数,但如果有双空格,则字数将不准确。有没有更好的方法来做到这一点?
【问题讨论】:
标签: c# regex text-parsing
@Martin v. Löwis 的替代版本,它使用 foreach 和 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;
}
【讨论】:
虽然基于 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;
}
效率更高(另外它还可以考虑额外的空白字符)。
【讨论】:
这似乎对我有用:
var input = "This is a test";
var count = input.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length;
【讨论】:
试试string.Split:
string sentence = "This is a sentence with some spaces.";
string[] words = sentence.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
【讨论】: