Java Count Number Of Words In A String
This is a user define java program to count number of words in a string using split method of string class.
Count Number Of Words Example
//How to Count Number Of Words import java.util.Scanner; class CountNumberOfWord{ static String str; static int count(String temp){ str=temp; String[] word = str.split(" "); int flag=0; for(int i=0;i<=word.length-1;i++){ flag+=1; } return flag; } public static void main(String...s){ System.out.println("Please enter a sentence"); Scanner input=new Scanner(System.in); String str1= input.nextLine(); int k=count(str1); System.out.println("Total Number of Word in Entered Sentence are: "); System.out.println(k); } }
Output
Please enter a sentence Java Count number example Total Number of Word in Entered Sentence are: 4