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