This post will discuss how to determine if a string contains a char in C++.

1. Using string::find

We can use the string::find function to search for a specific character in a string. It returns the index of the first instance of the character or string::npos if the character is not present. The following is a simple example demonstrating its usage.

Download  Run Code

Output:

Character found

2. Using basic_string::contains

Starting from C++23, we can use the much-awaited std::basic_string::contains function to checks if the string contains the given substring. It returns true if the string contains the specified substring, false otherwise.

Download  Run Code

Output:

Character found

That’s all about determining if a string contains a char in C++.