统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John"
输出: 5
思路分析:使用一个大循环扫描字符串,嵌套两个小循环,一个用于跳过连续非空格的“单词”,一个用于跳过空格。
class Solution {
public:
int countSegments(string s) {
int strSize = s.size(), result = 0, index = 0;
//跳过起始端的空格
while (index < strSize && s[index] == ' '){
index += 1;
}
//扫描大循环
while (index < strSize){
result += 1;
//跳过“单词”循环
while (index < strSize && s[index] != ' '){
index += 1;
}
//跳过空格
while (index < strSize && s[index] == ' '){
index += 1;
}
}
return result;
}
};
方法二:使用stringstream流。用输入的字符串初始化流,每次从流中读取一个“单词”,会跳过空格。
class Solution {
public:
int countSegments(string s) {
string word;
int result=0;
stringstream myStrStream(s);//用s初始化流myStrStream
while(myStrStream>>word){//从流中获取字符串(会跳过空格)
result += 1;
}
return result;
}
};