如何在字符串的特定长度中计算特定单词。让我们考虑一下一个字符串-“足球是一款很棒的游戏,它是全世界最受欢迎的游戏,这不仅是一场比赛,而且还是各国共同欢聚的节日,也是最令人兴奋的时刻”。字符串的总长度为145。我想计算一下字符串的每100个字符中有多少个“是”。
让我们考虑长度为100的字符串的第一部分,即-“足球是一款很棒的游戏,它是全世界最受欢迎的游戏,它不仅是一款游戏,而且还是一款”。在这里,我们发现100个字符中有3个“是”。琴弦的其余部分是“为各国欢聚的节日,这也是最令人兴奋的”,它的长度为69,长度为1。
我可以从一个字符串中找到给定单词的数目,但不能从特定的字符串长度中找到。这是我的下面的代码-
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
答案 0 :(得分:1)
创建具有所需长度的子字符串,然后使用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开始到字符串末尾的子字符串。
答案 1 :(得分:1)
尝试以下代码:
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);
}
}