Java Topics

Count the number of words in a String

public class CountWordsInString {

public static void main(String[] args) {

String s=" hello world hi";

System.out.println("s= "+s);

int count=0;

for(int i=0;i<s.length()-1;i++) {

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

count++;

}

       System.out.println("count= "+count);

}

}

Output:

s=  hello world hi

count= 3