Java Program to Count Number of Words in Given String

In this post, we will see simple Java program to count number of words in given String.
In this post, we discuss three methods to count numbers of words in given input String.
Method 1
Split the input string with space , split() method returns string array then use length method to get number of words from string array.
strArray.length
Method 2
Split the input string with space, split() method returns string array then simply use counter to count number of words present in string array.
int count = 0;
for (String word : str.split(" ")) {
 count++;
}
Method 3
Use charAt() method to check if space present in input string, if space is present then increment the counter by 1.
int count = 1;

for (int i = 0; i < str.length() - 1; i++) {
    if ((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')) {
      count++;
    }
}
Let's write complete program to count number of words in given string.

Java Program to Count Number of Words in Given String

/**
 * Java Program to Count Number of Words in Given String
 * @author javaguides.net
 *
 */
public class CountNumberOfWordsInString {
 public static void main(String[] args) {
  method1();
  method2();
  method3();
 }

 private static void method1() {
  final String str = "java developers guide";
  String[] strArray = str.split(" ");
  System.out.println("Number of words in a string = " + strArray.length);
 }

 private static void method2() {
  final String str = "java developers guide";
  int count = 0;
  for (String word : str.split(" ")) {
   count++;
  }
  System.out.println("Number of words in a string = " + count);
 }

 private static void method3() {
  final String str = "java developers guide";

  int count = 1;

  for (int i = 0; i < str.length() - 1; i++) {
   if ((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')) {
    count++;

   }
  }
  System.out.println("Number of words in a string = " + count);
 }
}
Output:
Number of words in a string = 3
Number of words in a string = 3
Number of words in a string = 3
In above program, we have seen three ways to count number of words in given String.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Related String Programs

Note that these programs are asked in interviews.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course