Determine if a string contains a char in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string str = "C++20"; char c = '+'; if (str.find(c) != std::string::npos) { std::cout << "Character found" << std::endl; } else { std::cout << "Character not found" << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string str = "C++20"; char c = '+'; if (str.contains(c)) { std::cout << "Character found" << std::endl; } else { std::cout << "Character not found" << std::endl; } return 0; } |
Output:
Character found
That’s all about determining if a string contains a char in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)