Java Program to Count Number of Words in a String

Java Program to Count Number of Words in a String

Counting the number of words, lines etc are the most asked question in schools and collages and most of the students memorises the same concept which is written in the book or class notes but the real fun is in doing the same thing with many different ways, building our own logic and learning the new short-cuts, So In this post we will tell some different ways by which you can count the number of words present in a string and some cool short-cuts to make your code simple and clean!
Java Program to Count Number of Words in a String

Logic

When we are asked to count the number of words in an sentence then what we do is search the white spaces and do our counting because the white space tells us where the previous words ended and the next word will start after it. So our most basic approach for counting the the words while programming is search the white spaces and increment the counter.

Working With Logic
According to the above logic we created a function which will return the number of words present in the string argument passed to it, have a look.
static int countWords(String s){
        int c=0;
        s=s+" ";
        for(int i=0; i<s.length(); i++){
            if( (""+s.charAt(i)).equals(" ") ){
                c++; 
            }
        }
        return c;
    }

Above function is working great and follows our logic as well (really?).
What it does is count the number of spaces in a string and return the count. but

If our string is like this " This is a String ". Having extra space at the beginning and ending then?
To correct this bug we have to use trim() function at line 3 and make it like this:
s = s.trim() + " ";

So problem solved? Lets see

If the entered string is written by a genius like you than the above logic will work for you because we know every word is separated by a single space but lets say you are reading the string from an text file and that file have strings like this " Hello      Java     Programmer      !" means a lots of spacing between words than this logic will completely fails!

Fixing The Bug
So, the above code can be fixed if we look for the words not just counting the occurrence of spaces.
And what we have to do is also read the next character to the space for checking whether the next word actually started or not!
Look at the final source code given below.

Source Code

class wordsCount {
    static int countWords(String s){
        int c=0;    //counting variable
        s=s.trim(); //removing extra spaces from begining and ending
        if(s.equals("")){
            return 0; //String is emply
        } else{
            s+=" "; //adding extra space for counting the last word
        }
        for(int i=0; i<s.length(); i++){
            if( (""+s.charAt(i)).equals(" ") ){ //if char is space
                
                if( i<s.length()-1 && (""+s.charAt(i+1)).equals(" ") ){ //also checking the next index
                    continue;
                }
                
            } else{ //not space
                continue;
            }
            /* program will reach here only if the next
             * character to the space is not a space
             */
            c++; 
        }
        return c;
    }
    public static void main(String args[]){
        
        String s = "  We Love  Jave Programming! ";
        
        int count = countWords(s);

        System.out.println("Words Count: " + count);
        
    }
}

Output

Words Count: 4


Short-cut Method For  Counting Words in a String

class Main1 {
    public static void main(String args[]){
        
        String s = "Code Nirvana Rocks";
        
        int count = s.trim().split(" ").length; //that's it!

        System.out.println("Words Count: " + count);
        
    }
}

Conclusion

So the long discussion on counting the number of words finally comes to an end :)
The short-cut method is great but will not work if your words are spaced my more than one white spaces.
So its your choice which code is suitable for your program and if you know any other method for counting the words of a string then do share with us, we really want to hear from you.

If you like this post than please like and share this with your friends and you can subscribe to our newsletter to get updated with our latest post on programming.

7 Comments Leave new

Enter a Number: 10

@ 2 3 4 5 6 7 8 9 10
2 @ 6 8 10 12 14 16 18 20
3 6 @ 12 15 18 21 24 27 30
4 8 12 @ 20 24 28 32 36 40
5 10 15 20 @ 30 35 40 45 50
6 12 18 24 30 @ 42 48 54 60
7 14 21 28 35 42 @ 56 63 70
8 16 24 32 40 48 56 @ 72 80
9 18 27 36 45 54 63 72 @ 90
10 20 30 40 50 60 70 80 90 @
how can i do this output ?

Reply
This comment has been removed by a blog administrator.

Sir please write a program for making a Stack using Linked List(without collections) with explanation, I have code but unable to understand it :/
Thanks in advance :)

Reply

can u write the program in scanner class for removing the duplicates from the string entered
input: LITTLE
output: LITE

Reply

It can be done easily by using contains property of String.
Check this code:

import java.util.Scanner;
class Main {
  public static void main(String[] args){  
    Scanner scan = new Scanner (System.in);
    String in , temp , out="";
    in = scan.nextLine();
    for(int i=0;i<in.length();i++){
        temp = ""+in.charAt(i);
        if(!out.contains(temp)){
            out+=temp;
        }
    }
    System.out.println(out);
  }
}

Reply

print pattern in java and c

_ 1 1 _
1 1 1 1
_ 1 1 _

Reply

import java.util.*;
class dup
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a word");
String str=s.next();
String sum="";
int i,j;
char ch,ch1;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch!=' ')
{
for(j=0;j<str.length();j++)
{
ch1=str.charAt(j);
if(ch==ch1)
{
str=str.replace(ch,' ');
sum+=ch;
}
}
}
}
System.out.println("Reduced word: "+sum);
}
}

Reply

Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.