Java program to count occurrences of a word in string

Java 8Object Oriented ProgrammingProgramming

The number of times a word occurs in a string denotes its occurrence count. An example of this is given as follows −

String = An apple is red in colour.
Word = red
The word red occurs 1 time in the above string.

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
public static void main(String args[]) {
String string = "Spring is beautiful but so is winter";
String word = "is";
String temp[] = string.split(" ");
int count = 0;
for (int i = 0; i < temp.length; i++) {
if (word.equals(temp[i]))
count++;
}
System.out.println("The string is: " + string);
System.out.println("The word " + word + " occurs " + count + " times in the above string");
}
}

Output

The string is: Spring is beautiful but so is winter
The word is occurs 2 times in the above string

Now let us understand the above program.

The values of the string and word are provided. Then the string is split by spaces in temp. A for loop is used to find if the word is available in temp. Each time it happens, count is incremented by 1. The code snippet that demonstrates this is given as follows −

String string = "Spring is beautiful but so is winter";
String word = "is";
String temp[] = string.split(" ");
int count = 0;
for (int i = 0; i < temp.length; i++) {
if (word.equals(temp[i]))
count++;
}

The string and the value of count i.e. number of times the word occurs in string is displayed. The code snippet that demonstrates this is given as follows −

System.out.println("The string is: " + string);
System.out.println("The word " + word + " occurs " + count + " times in the above string");
raja
Published on 05-Dec-2018 13:00:59
Advertisements