Count Number of Words in a String in Java

import java.util.*;

class WordsCount

{

public static void main(String arg[])

{

int word=1;

Scanner in=new Scanner(System.in);

System.out.println(“Enter your sentence:[Try to ignore space at end]”);

String str=in.nextLine();

for(int i=0;i<str.length();++i)

{

if(str.charAt(i)==’ ‘)

word++;

}

System.out.println(“Number of words=”+word);

}

}

Share with your Friends...
Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *