# 434.Number of Segments in a String

**434.Number of Segments in a String**

难度:Easy

> 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;
        bool ischar=false;
        if(s.empty()) return res;
        if(s.size()==1) return s[0]!=' ';

        for(int i=1;i<s.length();i++)
            if((s[i]==' ') && (s[i-1] !=' '))
            {
                res++;
                //cout<<" "<< i<< res<<" "<<s[i]<<" "<<s[i-1]<<endl;
                ischar=false;
            }
            else if(s[i]!=' ')
                ischar=true;
            
        return res+ischar;
    }
};
```

> 执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户\
> 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了90.29%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/434.number_of_segments_in_a_string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
