Java Program to Count Number of Words in a String

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 to count number of words in a String 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.

Java code to count number of words in a String

The following Java program shows both of the ways to count number of words in a String as discussed above.

Output

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

One Comment

  1. Pingback: Matrix Multiplication Java Program - KnpCode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.