以下是查找句子中给定单词出现次数的代码。
static void Main(string[] args)
{
string str;
string word;
int count = 0;
str = Console.ReadLine();
word = Console.ReadLine();
string[] str1 = str.Split(' ','.');
for (int i = 0; i < str1.Length; i++)
{
if (str1[i].Equals(word))
{
count++;
}
}
Console.WriteLine("No of occurrence of a word:" +count);
Console.ReadLine();
}
有没有最佳和优化的方法对此进行编码..?
答案 0 :(得分:4)
var occurences = yourString.Split().Count(word => word == wordToMatch);
答案 1 :(得分:0)
这样:
var query = from x in "String that contain words".Split().ToList()
group x by x into G
let Count = G.Count()
select new {Value = G.Key, Count = count};