# 434. Number of Segments in a String

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

``````**Input:** "Hello, my name is John"
**Output:** 5
``````

``````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;
}
};
``````

``````class Solution {
public:
int countSegments(string s) {
int res = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
++res;
}
}
return res;
}
};
``````

``````class Solution {
public:
int countSegments(string s) {
int res = 0;
istringstream is(s);
string t = "";
while (getline(is, t, ' ')) {
if (t.empty()) continue;
++res;
}
return res;
}
};
``````

Reverse Words in a String

https://discuss.leetcode.com/topic/70775/c-istringstream-try

https://discuss.leetcode.com/topic/70642/clean-java-solution-o-n

https://discuss.leetcode.com/topic/70656/ac-solution-java-with-trim-and-split

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation