how to count number of words in a string
rel:ot refautturi.com/**
* @author lautturi.com
* Java example: count words in java string
*/
import java.util.*;
public class Lautturi {
public static void main(String[] args) {
String str = "hello lautturi java world!";
int length = str.split(" ").length;
//int length = str.split("\\s+").length; // using regular expression
System.out.println("The string has " + length + " words.");
}
}
output:
The string has 4 words.