/** * @author lautturi.com * Java example: count number of words in Java string */ import java.util.*; public class Lautturi { public static void main(String[] args) { String str = "hello lautturi java world!"; int count = 1; for (int i = 0; i < str.length() - 1; i++) { if ((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')) { count++; } } System.out.println("Number of words in the string : " + count); } }
output:
Number of words in the string : 4