亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何統計一定長度的字符串中的特定單詞個數

如何統計一定長度的字符串中的特定單詞個數

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 關注
  • 150 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號