![](/img/trans.png)
[英]In C#, what is the recommended way to establish whether or not a string is a real word?
[英]What is a Surefire way to get a string Word Count in C#
我不确定该怎么做。 现在,我正在计算空格以获取字符串的字数,但是如果存在双倍空格,则字数将不准确。 有一个更好的方法吗?
@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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.