Java program to count words in a given string

Java 8Object Oriented ProgrammingProgramming

The words in a given string can be counted using a while loop. An example of this is given as follows −

String = Sky is blue
Number of words = 3

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String args[]) {
      int flag = 0;
      int count = 0;
      int i = 0;
      String str = "The sunset is beautiful";
      while (i < str.length()) {
         if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') {
            flag = 0;
         }else if (flag == 0) {
            flag = 1;
            count++;
         }
         i++;
      }
      System.out.println("The string is: " + str);
      System.out.println("No of words in the above string are: " + count);
   }
}

The output of the above program is as follows.

Output

The string is : The sunset is beautiful
No of words in the above string are : 4

Now let us understand the above program.

First, the string str is defined. Then a while loop is used to obtain the number of words in the string. This is done using the flag variable that is initially initialized to 0. The code snippet that demonstrates this is given as follows.

int flag = 0;
int count = 0;
int i = 0;
String str = "The sunset is beautiful";
while (i < str.length()) {
   if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') {
      flag = 0;
   }else if (flag == 0) {
      flag = 1;
      count++;
   }
   i++;
}

Finally, the string and the number of words in it are displayed. The code snippet that demonstrates this is given as follows.

System.out.println("The string is: " + str);
System.out.println("No of words in the above string are: " + count);
raja
Published on 05-Dec-2018 12:19:49
Advertisements