如何统计一定长度的字符串中的特定单词个数

如何计算特定长度字符串中的特定单词。让我们考虑一个字符串——“足球是一项伟大的运动,它是全世界最受欢迎的运动,它不仅是一种运动,而且还是一个万国欢聚的节日,这也是最令人兴奋的”。字符串的总长度是145。我喜欢统计每100个字符串中有多少个'is'。


让我们考虑长度为 100 的字符串的第一部分,即 - 'Football is a great game It is most popular game over the world It is not only a game but also'。在这里,我们在 100 个字符中找到了 3 个“是”。字符串的其余部分是 -'a festival of get together for the nations which is most exciting too' 其长度为 69,并且该长度中有 1 个“is”。


我可以从字符串中找出给定单词的数量,但不能从特定长度的字符串中找出。下面是我的代码 -


string word = "is";

string sentence = "Football is a great game It is most popular game all over the world It is not only a game but also a festival of get together for the nations which is most exciting too";

int count = 0;

foreach (Match match in Regex.Matches(sentence, word, RegexOptions.IgnoreCase))

{

    count++;

}

Console.WriteLine("{0}" + " Found " + "{1}" + " Times", word, count);`

输入:


string - '足球是一项伟大的运动,它是全世界最受欢迎的运动,它不仅是一项运动,也是一个万国欢聚的节日,也是最令人兴奋的'


词-'是'


长度 - 100


输出:


在第一部分:给定单词的数量 = 3


在第二部分:给定单词的数量 = 1


胡说叔叔
浏览 113回答 2
2回答

倚天杖

试试这个代码:public class JavaApplication22 {    public static void main(String[] args) {        String str = "Football is a great game It is most popular game all over the world It is not only a game but also a festival of get together for the nations which is most exciting too";        String pattern = "is";        int count = 0;        int a = 0;        while((a = str.indexOf(pattern, a)) != -1){            a += pattern.length();            count++;        }        System.out.println("Count is : " + count);    }}

肥皂起泡泡

创建一个具有所需长度的子字符串,然后使用 linq 进行计数。int length = 100;string word = "is";string sentence = "Football is a great game It is most popular game all over the world It is not only a game but also a festival of get together for the nations which is most exciting too";//Substring with desired lengthsentence = sentence.Substring(0, length);int count = 0;//creating an array of wordsstring[] words = sentence.Split(Convert.ToChar(" "));//linq querycount = words.Where(x => x == word).Count();Debug.WriteLine(count);对于第二部分,创建一个从 100 开始到字符串末尾的子字符串。
打开App,查看更多内容
随时随地看视频慕课网APP