Write a Java program to count number of words and characters in a text or string, the following java program has been written in multiple ways along with sample outputs as well.
This code is for counting the number of words in a user input string using Java language.
- The problem here is to count the number of words in a string that is defined by user input.
- Our constraint here is the inability to get the correct word count in the event of the user input string containing white-spaces at the beginning of the string.
- The input here is a sentence in the form of a string input by the user.
- The output here is the count of number of words present in the user-defined input string.
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.Scanner; class GetWordCount { public static void main(String arg[]) { int i,count=1; Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); String name = sc.nextLine(); for(i=0;i<name.length();i++) { if(name.charAt(i)==' '&&name.charAt(i+1)!=' ') { count++; } } System.out.print("word count of("+name+")---------->"+count); } } |
Output:
- Solution :
- The first line in the main method declares int i and int count and initializes the value of count to 1.
- Then, a new Scanner class object is initialized and a reference variable sc is set to represent the object. This class is used to take user input in Java. Scanner class is part of the java.util package and hence the import statement in the beginning is stated to import the functionality of the specified class.
- The next line prints a statement to the console instructing the user to enter a string.
- The .nextLine() method is called by the Scanner object sc. This method reads a line of user input of a string value and stores it to the string variable name.
12345for(i=0;i<name.length();i++) {if(name.charAt(i)==' '&&name.charAt(i+1)!=' ') {count++;}} - This loop iterates over all the characters (including the white-spaces and other special characters which are also considered as characters in Java) in the user-defined string.
- For each iteration, a conditional statement checks whether the character in consideration is a whitespace and the next character is not a white-space. It is essentially checking if the given character is a white-space between two words.
- The count is incremented by 1 if this condition is satisfied. Keep in mind that the first word is not counted using this technique and hence the value of count is initialized to 1 and not 0.
- The print statement in the end of the main method prints out the input and the counted number of words in the input as the output.
1 2 3 |
Enter the string hello world welcome to java tutoring word count of(hello world welcome to java tutoring)---------->6 |