Categories
Interview java String

count number of words in string using java

In this post, we will learn about count number of words in string using java

In below example we using split method to count number of words in a sentence.

If String have more than one space consecutively, then we need to replace with one string using below code

sentence.replaceAll("\\s+", " ").trim();
Syntax
properString.split(" ");
Example using split
public class CountWords {

	public static void main(String[] args) {

		try {
			String sentence = "    The pen    is mightier than the sword . ";
			String properString = sentence.replaceAll("\\s+", " ").trim();
			String[] split = properString.split(" ");
			System.out.println("The sentence have " + split.length + " words");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
The sentence have 8 words
Example using StringTokenizer
import java.util.StringTokenizer;

public class CountWords {

	public static void main(String[] args) {
		try {
			String sentence = "    The pen    is mightier than the sword . ";
			StringTokenizer tokens = new StringTokenizer(sentence);
			System.out.println("The sentence have " + tokens.countTokens() + " words");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
The sentence have 8 words
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/strings/CountWordsUsingSplit.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/strings/CountWordsUsingTokenzier.java

Related Articles

find the first occurrence of a character in string using java

Leave a Reply

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