统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: “Hello, my name is John”
输出: 5
打完,!*这些特殊符号之后都会有个空格所以不用管,只算空格就otmk,此题题意有点tricky
class Solution {
public int countSegments(String s) {
if(s.length() == 0 || s.trim().isEmpty()) return 0;
String str = s.trim();
int count = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ' ' && str.charAt(1+i) != ' ') count++;
}
if(count == 0) return 1;
return count+1 ;//把字段里的特殊符号算上(特殊符号打完都有个空格:hey, joe)
}
}