In this tutorial you will learn about the Java program to count number of words in sentence and its application with practical example.
Java program to count the number of words in a sentence
In this tutorial, we will learn to create a Java program that will count the number of words in a sentence in Java programming
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Conditional Statements in Java programming.
What is a Sentence?
As we all know, a sentence is a collection of characters and words. The word is a collection of alphabets. For string, only one variable is declared which can store multiple values. The String can consist of all the typeable data, it means Digits, Alphabets, Symbols, etc.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input string from the user. 3. Passing those variables to for loop. 5. Using conditional statements for the program to find all the word occurrence of in that sentence. 6. Printing the result. 7. End the program. |
Count the number of words in a sentence
In this program, first, we will declare the input string in the program. Then we will declare the word to be searched in the sentence. Then will find the occurrence of that word in that string. Printing the result if that string is present in the sentence or not.
Let us take the example program from the below code to search for the occurrence of that word.
Program:-
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 26 |
import java.util.*;//Importing the util package in the program. public class WordCounting { static int wordcount(String string) { //Using a counter variable int count=0; //Counting the words in the sentence. char ch[]= new char[string.length()]; for(int i=0;i<string.length();i++) { ch[i]= string.charAt(i); if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) ) count++; } //Printing the output number of words return count; } public static void main(String[] args) { //declaring the required variable for the program. String string =" W3adda is a good place to learn"; //Printing the ouput number of words. System.out.println(wordcount(string) + " words."); } } |
Output:-
In the above program, we have first initialized the required variable.
- txt = It will hold the string value.
- str1 = It will hold the string value.
Count the words in the sentence using a conditional statement.
Logic code of the user-defined functions
Printing output number of words in the sentence.