In this post we’ll see Java program to count number of words in a String. You can use split() method provided by the Java String class with the regular expression “\\s+” to match any number of white spaces. split() method returns an array which contains each substring of this string that matches the given expression. The length of this array will be the count of words in the String.
If you are specifically ask to write the Java program without using any API method then you can use the logic where you check each character of the string whether it is a space or not. If it is a space that means word has ended then you can increment the count.
Count number of words in a String Java program
The following Java program shows both of the ways to count number of words in a String as discussed above.
public class CountWords { public static void main(String[] args) { CountWords.stringWordCount("This program is to count words"); CountWords.wordCountUsingSplit("count words using split "); } public static void stringWordCount(String str){ int count = 1; for(int i = 0; i < str.length() - 1; i++){ // If the current char is space and next char is not a space // then increment count if((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')){ count++; } } System.out.println("Count of words in String - " + count); } // This method uses split method to count words public static void wordCountUsingSplit(String str){ // regex "\\s+" matches any number of white spaces String[] test = str.trim().split("\\s+"); System.out.println("Count of words in String - " + test.length); } }
Output
Count of words in String - 6 Count of words in String – 4
Related Posts
- Java Program to Count The Frequency of Each Character in a String
- Java Program to Find Duplicate Characters in a String With Repetition Count
- Convert Char to String And String to Char in Java
- How to Convert String to double in Java
- Java Program to Reverse Each Word in a String
- Java Program to Check Whether Number Prime or Not
- How to Get The Last Modified Date of a File in Java
- Java Program to Convert Between Time Zones
That’s all for the topic Java Program to Count Number of Words in a String. If something is missing or you have something to share about the topic please write a comment.
You may also like