Java Program to Count Number of Words in a String

In this tutorial, I am going to explain a java program to count number of words in a string.

Given an input string, write a code to count number of words in a string. The words in a string are separated by space(‘ ‘).

For example –

Example 1

Input – “Java Programming question”
Output – 3

Example 2

Input String – “Programming Tutorials”
Output – 2

Count Number of Words in a String

Programming video tutorials

Algorithm to Count Number of Words in a String

To count a number of words in a String. Traverse a string and check if a current character is a space and the next character is not space then increment the word count by 1.

Java Program to Count Number of Words in a String

Let’s write a java code for the discussed algorithm. In this programming example, we are writing a code a word count program in java.

The time complexity of this approach is O(n).

Wrapper classes in java

Find first non-repeating character in a string

METHOD 2:

Java Program to Count Number of Words in a String using Split

Using the split() method in java we can solve this problem in single line of code. In this solution, we use the regular expression “\\s+” to split the string on whitespace. The string split method returns an array, if we print the length of an array that is the number of words in a given string.

Video Tutorial

In this video tutorial, I have explained the logic of counting number of words in a string.

How to Count Number of Words in a String – Java

C programming questions for practice

How to create immutable class in java

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.