为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
胡说叔叔 2023-04-29 18:07:05
如何计算特定长度字符串中的特定单词。让我们考虑一个字符串——“足球是一项伟大的运动,它是全世界最受欢迎的运动,它不仅是一种运动,而且还是一个万国欢聚的节日,这也是最令人兴奋的”。字符串的总长度是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
查看完整描述

2 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

试试这个代码:


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);

    }

}


查看完整回答
反对 回复 2023-04-29
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

创建一个具有所需长度的子字符串,然后使用 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 length

sentence = sentence.Substring(0, length);

int count = 0;

//creating an array of words

string[] words = sentence.Split(Convert.ToChar(" "));

//linq query

count = words.Where(x => x == word).Count();

Debug.WriteLine(count);

对于第二部分,创建一个从 100 开始到字符串末尾的子字符串。


查看完整回答
反对 回复 2023-04-29
  • 2 回答
  • 0 关注
  • 112 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信