题目描述:
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
要完成的函数:
int countSegments(string s)
说明:
这道题目相当容易。segment定义为不包含空格字符的连续字符串,要求返回一个字符串中有多少这样的segment。
考虑一下边界条件,比如最开始是连续几个空格字符,接下来才是“正经字符”,比如最后以空格结尾,不带空格结尾。
代码如下:
int countSegments(string s)
{
int i=0,count=0;
while(i<s.size())
{
if(s[i]==' ')
i++;
else
{
count++;
while(s[i]!=' '&&i<s.size())//这里的判断条件也可以换成
i++; //s[i]!=' '&&s[i]!='\0'
}
}
return count;
}