以空格爲分隔符,判斷一個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; } };