Beginners Programs :

Java : Get Word Count In String – 4 Ways | Java Programs

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.

Output:

  • Solution :
  1. The first line in the main method declares int i and int count and initializes the value of count to 1.
  2. 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.
  3. The next line prints a statement to the console instructing the user to enter a string.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.