In this tutorial, we will see a simple java program to count number of words in sentence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Scanner; public class StringOperator { public static int countWordsinStr(String str){ int count = 1; for(int i=0; i<=str.length()-1; i++){ if(str.charAt(i) == ' ' && str.charAt(i+1)!=' '){ count++; } } return count; } public static void main(String args[]){ String str; Scanner scan = new Scanner(System.in); System.out.print("Enter a Sentence : "); str = scan.nextLine(); System.out.print("Total number of words are " + countWordsinStr(str)); } } |
Output:
Enter a Sentence : Java2Blog is a technical blog.
Total number of words are 5
Total number of words are 5
That’s all about Java program to count number of words in sentence.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.