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
Related Articles
find the first occurrence of a character in string using java