Topic:
the number of words in a string of statistics, the word here refers to the continuous character is not a space.
Note that you can assume that the string was does not include any non-printable characters.
Example:
Enter: "Hello, my name is John "
Output: 5
public int countSegments(String s) {
String str = s.trim();
if(str.length() == 0)
return 0;
int ans = 0;
for(int i=0;i<str.length();i++){
//非空直接跳过去,只有空串+1
if(isEmpty(str.charAt(i))){
ans++;
//将连续空格跳过去
while(i!=str.length() && isEmpty(str.charAt(i)))
i++;
}
}
return ans +1;
}
public boolean isEmpty(char c ){
return c==' ';
}