Java Program to Count Number of Words in a String

In this tutorial, I have explained 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

Java Program to Count Number of Words in a String

Java Program to Count Number of Words in a String

 

Programming video tutorials

Subscribe Our Tutorials

Get Latest Updates on Facebook

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

In this programming example, I have written a java code to count number of words in a string.

 

Find first non-repeating character in a string

METHOD 2:

Using the split() method in java we can solve this problem in single line of code.

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

C programming questions for practice

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.