
以空格为分隔符,判断一个string可以被分成几部分。
注意几种情况:(1)全都是空格 (2)空字符串(3)结尾有空格
思路:
只要统计出单词的数量即可。那么我们的做法是遍历字符串,遇到空格直接跳过,如果不是空格,则计数器加1,然后用个while循环找到下一个空格的位置,这样就遍历完了一个单词,再重复上面的操作直至结束,就能得到正确结果:
class Solution {
public:
int countSegments(string s) {
int res = , n = s.size();
for (int i = ; i < n; ++i) {
if (s[i] == ' ') continue;
++res;
while (i < n && s[i] != ' ') ++i;
}
return res;
}
};