> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/434.number_of_segments_in_a_string.md).

# 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
