题目:
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
思路:
本题,利用c++标准库函数,其中要注意的是标点符号后面还会有空格,所以直接忽略标点符号。
代码:
class Solution {
public:
int countSegments(string s) {
int sum=0;
if(s.size()==0)
return 0;
for(int i=0;i<s.size();i++)
{
if(isspace(s[i]))
sum++;
}
return sum+1;
}
};