Write a java program to count the word occurrences in the string

Write a java program to count the word occurrences in the string. Write a program to read a string that contains a sentence and read a word. Check the number of occurrences of that word in the sentence.

Note: The check is case-sensitive.

Input and Output Format:

Input consists of two strings.
The output consists of a count indicating the number of occurrences.
Refer sample output for formatting specifications.

Sample Input 1:
Hello world Java is the best programming language in the world
world

Sample Output 1:
2

Sample Input 2:
hello world
World

Sample Output 2:
0

java program to count the word occurrences in the string

import java.io.IOException;
import java.text.ParseException;
import java.util.*;
 
public class Main {
 
public static void main(String[] args) throws IOException, ParseException  {
// TODO Auto-generated method stub
String s1="hello world hello";
String s2="World";
int c=0;
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens())
{
String s3=t.nextToken();
if(s3.equals(s2))
c++;
}
System.out.println(c);
}
}

Add a Comment

Your email address will not be published. Required fields are marked *

two × five =