C#计算字符串中的单词数



如何使用基本的字符串函数和循环?我想数一串单词。我的问题是,只有当用户不使用多个空格时,它才有效。

这是我的代码:

string phrase;
int word = 1;

Console.Write("Enter a phrase: ");
phrase = Console.ReadLine();
for (int i = 0; i<phrase.Length; i++)
{
if (name[i] == ' ')
{
word++;
} 
}
Console.WriteLine(word);

一种方法是使用正则表达式;浓缩";将所有连续的空间合并到单个实例中。那么工作就简单了。

var str = "aaa bb      cccc d    e";
var regex = new Regex(@"s+");
Console.WriteLine(regex.Replace(str, " ")?.Split(' ')?.Count());

如果您可以使用LINQ,我建议使用这种方法:

string[] source = phrase.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
var matchQuery = from word in source
select word;

int wordCount = matchQuery.Count();
Console.WriteLine(wordCount);

我会创建一个具有字符串数据类型的数组。然后我会在读取数据时使用Split方法。只要你看到一个定义的字符(字符是一个字母或字符(,这就会分割整个文本。在您的情况下,定义的字符将是空格;那就是"。所以我的公式应该是:

string phrase;
string[] seperated;    // this is where you would split the full name
int word = 1;

Console.Write("Enter a phrase: ");
phrase = Console.ReadLine();
seperated=phrase.Split(' ');
for (int i = 0; i<seperated.Length; i++)
{
Console.WriteLine(seperated[i]); // this would print each word one by one
}

一旦在单独的数组中捕获完整的名称拆分,您就可以按照自己的意愿使用单独的名称、姓氏等。separated[0]=将是第一个单词,separated[1]将是第二个单词。。。如果名称总共由5个单词组成,则最后一个单词可以通过分隔符[4]到达。

您可以使用Split((和Linq:来代替for循环

var splitPhrase = phrase.Split(' ');
var wordCount = splitPhrase.Count(x=>x != "");

或者根据注释使用StringSplitOptions:

var words = phrase.Split(' ', StringSplitOptions.RemoveEmptyEntrie);
var wordCount = words.Count();

您可以使用正则表达式模式:\S匹配除空白之外的任何内容

string str = "Test words   test"    
MatchCollection collection = Regex.Matches(str, @"[S]+");
int numberOfWords = collection.Count;

首先,我们必须定义单词。如果单词是

任何非空的字母序列

我们可以使用一个简单的正则表达式模式:p{L}+

代码:

using System.Text.RegularExpressions;
...
int word = Regex.Matches(phrase, @"p{L}+").Count;

编辑:如果您不想要正则表达式,您可以实现FSM-FiniteStateM机器:

int word = 0; 
bool inWord = false;
foreach (var c in phrase) 
if (char.IsLetter(c)) {
if (!inWord) // we count beginnings of each word
word += 1;
inWord = true;
}
else
inWord = false;

这里我们有两种状态:-inWord == true, false,即字符是否在某个单词中。有了这些状态,我们可以数出所有单词的开头。

您可以通过使用以下函数来实现这一点。它只返回给定句子中的字数。

public int totalWords(string sentence) {
int wordCount = 0;
for (int i = 0; i < sentence.Length - 1; i++)
{
if (sentence[i] == ' ' && Char.IsLetter(sentence[i + 1]) && (i > 0))
{
wordCount++;
}
}
wordCount++;
return wordCount;
}

假设你的单词被一个空格隔开,你只需要Split字符串,就可以得到结果数组的长度:

string[] words = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
int numberOfWords = words.Length;

相关内容

最新更新