Count number of words in java.

Following code will help to count the number of words in given string.

String str = “i  am     reading    this book  since yesterday.”, space = ” “;
/* int spaces = 0;

for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == ' ' && str.charAt(i + 1) != ' '
&& str.charAt(i + 1) != '.') {

spaces++;
}

}
spaces++;
System.out.println("No. Of words =" + spaces);

Posted from WordPress for Android

Advertisements