13. Program to count number of words in a String?
class Main{
static int wordCount(String str){
int count = 0, len = str.length();
for(int i = 0; i < len; i++){
if(Character.isDigit(str.charAt(i))){
while(str.charAt(i) != ' ' && (i+1) != len){
i++;
}
}
else{
if((str.charAt(i) == ' ' || (i+1) == len) && Character.isLetter(str.charAt(i-1))){
count++;
}
}
}
return count;
}
public static void main(String[] args){
int count = wordCount("Java is a Programming Language");
System.out.println("Number of words in string is : " + count);
}
}
OUTPUT
Number of words in string is : 5