> For the complete documentation index, see [llms.txt](https://mr-poston-1.gitbook.io/c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mr-poston-1.gitbook.io/c++/1.-c++-basics/1.4-loops/1.4.4-searching-a-string.md).

# 1.4.4 Searching a String

Like other languages, C++ allows us to search a string for a value, however the syntax is a little different compared to languages like Java.

### Find Command

In C++, you use the `find` command to search a string. If the string is found, the position where the first instance is found is returned.

When the string is not found, the string no position value is returned. This value is represented as `string::npos`.

Here is an example of the syntax to search for a `cat`.

```
string str = "alley cat";
if(str.find("cat") != string::npos) {
    cout << "I found a cat!" << endl;
}
```

## Assigning a Value While Evaluating

One of the more unique features of C++ is that you can assign a value in the same statement that you evaluate it. This allows you to combine statements in a logical way. For example, if you wanted to find whether a phrase contained `cat` and print the position only if it does, you can do something like this:

```
int found;
if((found = str.find("cat")) != string::npos) {
    cout << "I found a cat at position ";
    cout << found << endl;
}
```

Notice that the variable was declared before the conditional statement and the variable assignment is in parenthesis so that it is created before evaluating.

### Try This Example

{% embed url="<https://onlinegdb.com/xkEj7ozzf>" %}
Searching a String
{% endembed %}


---

# 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://mr-poston-1.gitbook.io/c++/1.-c++-basics/1.4-loops/1.4.4-searching-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.
