Write a java program to find String Occurrences in the sentence

Java program to find String occurrences in the sentence, Obtain two strings from user as input. Your program should count the number of occurrences of the second word of the second sentence in the first sentence. Return the count as output. Note – Consider the case.

 Input and Output Format

  • Input consists of two strings with a maximum size of 100 characters.
  • Output consists of a single string.

Refer sample output for formatting specifications

Sample Input 1:

abc bcd abc bcd abc abc

av abc

Sample Output 1:

4

Sample Input 2:

ABC xyz AAA

w abc

Sample Output 2:

0

Java program to find  String Occurrences in the sentence

Following are the steps to find the occurrence of a string in  the sentence:

  • Input two strings from the user.
  • Call the getvalues() method with both the string.
  • Inside the method, initialize the count variable to 0.
  • Now, break the string into tokens.
  • Iterate over the string, get each token from the string tokenizer. If the token from the second input string matches with the first string then increment the count.
  • At last, just print the count.
import java.util.StringTokenizer;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1= sc.nextLine();
String s2= sc.nextLine();
getvalues(s1,s2);
}
public static void getvalues(String s1, String s2) {
int count=0;
StringTokenizer st=new StringTokenizer(s2," ");
String s3=st.nextToken();
String s4=st.nextToken();
//System.out.println(s4);
StringTokenizer st1=new StringTokenizer(s1," ");
while(st1.hasMoreTokens())
{
String s5=st1.nextToken();
if(s4.equals(s5))
{
count++;
}
}
System.out.println(count);
}
}

Output

Thus, this is how we find the count of occurrence of a word in a sentence.