Table of Contents

In Java, to count total number of words in a string we can use in-built function such as split() method or whitespace counting approach or we can also create a custom method.

For instance, “I love programming” contains 3 words, resulting the word count to 3.

In this article we will learn how to count total number of words in a string through an example, detailed logic and program explanation for better understanding.

📘 Required Knowledge

  • Java programming basics
  • Loop concepts
  • Conditional statements
  • String methods

📝 Problem Statement

We need to write a Java program that ask the user to enter a sentence or a string. The program should then count the total number of words present in the input string. Words are typically separated by one or more spaces. This program will handle the logic to identify individual words and calculate the count accordingly.

Example:

For a given input string str, “Hello, This is Interview Expert”, Output should be “count of words in the String str is 5”.

Explanation:

Input String str: "Hello, This is Interview Expert".

Here, we will count only the words and we will not count the spaces.

In the above String, there are 5 words are present:
"Hello,", "This", "is", "Interview", "Expert".

Hence, count of words in the String str is 5.

💡Logic to count total number of words in a string

There are multiple logics to count total number of words in a string in Java programming language.

Logic 1: Using split() function

  • To count the number of words in a given string using split() function, first Initialize the str variable with input string given by the user.
  • Remove trailing and leading spaces using trim() method.
  • Split the input string (str) into an array of words using the split(“\s+”) method. This method splits the string based on one or more consecutive spaces.
  • After splitting into array of words, use length property to count the number of words present in the string.

Logic 2: Whitespace counting approach

  • In Whitespace counting approach: Initialize the str variable with the input string given by the user. Remove leading and trailing spaces using the trim() method.
  • If the trimmed text (str) is empty or contains only whitespace characters, set the count to 0.
  • If the text is not empty, initialize the count to 1 since there is at least one non-space character present.
  • Iterate through the text from index 0 to the length of the string using a for loop.
  • Inside the loop, check if the current character is a space (” “) and the next character is not a space (to avoid double counting spaces) using an if statement.
  • If this condition is met (current character is a space and next character is not a space), increment the count.
  • Continue iterating until the loop reaches the end of the string (str.length()). After exiting the loop, print the count, which represents the total number of words in the input text.

Logic 3: Custom method

  • In custom method approach: Create a custom method that takes a string as input to count the number of words.
  • Check if the input string is null, empty, or contains only whitespace characters using an if statement:
    • If true, return 0 to indicate no words are present.
  • Initialize a count variable to 1:
    • This assumes there is at least one word when the string is not empty.
  • Use a for loop to iterate through the string from index 0 to str.length()-1.
  • Inside the loop, check if the current character is a space (” “) and the next character is not a space using an if statement:
    • If true, increment the count to track words properly and avoid counting consecutive spaces.
  • After the loop exits, return the count, which represents the total number of words in the input text.
  • Call this custom method from the main method to display the result.

🧮Java program to count the total number of words in a string

✅ Program 1: Using split() function

In the below program we are using split() function to count the total number of words in a string in Java.

import java.util.Scanner;
public class CountingWordsOfString {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the text :");
		String str = s.nextLine();
		str=str.trim();
		String[] words = str.split("\\s+"); 
		System.out.println("Total word count in string: "+ words.length);
		s.close();
	}
}

Output:

Enter the text :
Welcome to the Interview Expert
Total word count in string: 5

🧠 Explanation:

  1. The program begins by importing the Scanner class from the java.util package.
  2. It contains a main method, within the main method, it initializes a Scanner object named ‘s’ to read input from the console.
  3. User is asked to enter a text string.
  4. The input string is trimmed to remove leading and trailing whitespace.
  5. Then the input string is then split into an array of words using the split() method, which splits the string based on one or more space characters.
  6. Now, the program calculates the number of words in the input string by obtaining the length of the array.
  7. Finally, it prints the count of words in the input string to the console and closes the Scanner object to release system resources.

✅ Program 2: Whitespace Counting Approach

In the below program we are counting total number of words using whitespace counting approach in Java.

import java.util.Scanner;
public class CountingWordsOfString2 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the text:");
		String str = s.nextLine();
		str = str.trim();
		int count = 0;
		if (str.isEmpty()) {
			count = 0;
		} else {
			count = 1; 
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) == ' ' && str.charAt(i + 1) != ' ') {
					count++;
				}
			}
		}
		System.out.println("Total word count in string: " + count);
		s.close();
	}
}

Output:

Enter the text:
Hi, how is your learning??
Total number of words count: 5

🧠 Explanation:

  1. The program asks the user to input a text string.
  2. Program trims any leading or trailing whitespace from the input string.
  3. It initializes a count variable to track the number of words.
  4. If the input string is empty, the count is set to 0.
  5. Otherwise, the count is initialized to 1 to account for the first word.
  6. It iterates through each character of the input string.
  7. If a space character is encountered followed by a non-space character, the count is incremented.
  8. Finally, it prints the total number of words counted to the console.
  9. The program ensures accurate counting of words in the input string by considering spaces as word separators.
  10. Finally, the Scanner object is closed to release system resources.

✅ Program 3: Custom method

In the below program we are counting total number of words by creating a custom method in Java.

import java.util.Scanner;
public class CountingWordsOfString3 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the text :");
		String str = s.nextLine();
	        str = str.trim();
		int countStringWords=countingWords(str);
		System.out.println("Total word count in string: "+countStringWords);
		s.close();
	}
	public static int countingWords(String string)
	{
		if(string==null||string.isEmpty()||string.trim().isEmpty()) {
			return 0;
		}
		int count =1;// first character without space 1
		for(int i=0;i<string.length()-1;i++) {
			if(string.charAt(i)==' ' && string.charAt(i+1)!=' ') {
				count++;
			}
			}
		return count;
	}
}

Output:

Enter the text :
All the very best. Keep Learning
Total word count in string:: 6

🧠 Explanation:

  1. The program asks the user to enter a text string.
  2. Program trims any leading or trailing whitespace from the input string.
  3. It calls the countingWords method to count the number of words in the trimmed string.
  4. The countingWords method checks if the string is null, empty, or contains only whitespace and returns 0 if true.
  5. If the string is not empty, it initializes a word count to 1.
  6. It iterates through the string, checking for spaces followed by non-space characters, and increments the word count accordingly.
  7. The word count is printed to the console.
  8. The program closes the Scanner object to release system resources.

Conclusion

In this article, we have learnt how to count total number of words in a string in Java. We have seen the logic and implemented the program using split() method, Whitespace counting approach and by creating a custom method in Java. Hope this article helped you in the understanding of the program.

You can also check our other articles:

Happy Coding!!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in:

Java Coding,