Count Words in a String in JAVA

Count No. of Words in a String

To Count number of words in a string we have to count no of white spaces in the given string.
No. of words = No. of White Spaces + 1.

Example :-

Welcome to BluejCode!

Here : No. of white spaces are 2, So words are (No. of white spaces + 1) = 3 words
Program and Video Link given Below:-

Program :-

import java.io.*;
import java.util.*;
class Words
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        String str;
        char ch;
        int l,i,w=0;
        System.out.println("Enter Sentence");
        str = in.nextLine();
        l= str.length();
        for(i=0;i<l;i++)
        {
            ch= str.charAt(i);
            if(ch==' ')
            {
                w++;
            }
        }
        w=w+1;
        System.out.println("Original Sentence : "+str);
        System.out.println("No. of Words : "+w);
    }// end of class
}//end of main
       

Checkout Video of this Program : Click Here

All the Best :)
Keep Learning :

Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

PalPrime Number in JAVA