import java.util.Scanner; public class WordCount { public static void main(String args[]) { String text; int countWords=0; Scanner SC=new Scanner(System.in); System.out.print("Enter string: "); text=SC.nextLine(); //word count for(int i=0; i<text.length()-1; i++) { if(text.charAt(i)==' ' && text.charAt(i+1)!=' ') countWords++; } System.out.println("Total number of words in string are: "+ (countWords+1)); //since last word does not contain and character after that } }
Enter string: hello java Total number of words in string are: 2
Enter string: hello java Total number of words in string are: 3
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)