Reputation: 51
How to count a specific word in a specific length of a string. Let consider a string - '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'. The total length of the string is 145. I like to count how many 'is' are in each 100 characters of the string.
Let consider the first part of the string having length 100, that is - 'Football is a great game It is most popular game all over the world It is not only a game but also '. Here we found 3 'is' in 100 characters. The rest portion of string is -'a festival of get together for the nations which is most exciting too' which is 69 in length and having 1 'is' in this length.
I can find out number of given word from a string but not from a specific length of string.Here is my code below -
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);`
Input:
string - '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'
Word - 'is'
In length - 100
Output:
In first portion: number of given word = 3
In second portion: number of given word = 1
Upvotes: 0
Views: 3100
Reputation: 72
Try this code:
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);
}
}
Upvotes: 2
Reputation: 123
Create a substring with the desired length and then count using 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);
For the second portion create a substring starting at 100 to the end of your string.
Upvotes: 1