题目描述:

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
  • 2022-02-18
  • 2022-12-23
猜你喜欢
  • 2022-03-09
  • 2022-12-23
  • 2022-12-23
  • 2021-08-29
  • 2022-12-23
  • 2021-10-06
  • 2021-06-23
相关资源
相似解决方案