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 len = 0;
int n = s.length();
if(n == 0) return 0;
for(int i=0;i<n;i++)
{
if(s[i] == ' '&&i-1>=0&&s[i-1] != ' ')
++len;
}
if(s[n-1] != ' ')
++len;
return len;
}
};