HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Check if a string contains a string in C++

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringcheckcontains

Problem

I have a variable of type std::string. I want to check if it contains a certain std::string. How would I do that?

Is there a function that returns true if the string is found, and false if it isn't?

Solution

From C++23 you can use contains:

if (s.contains(substr)) {
    // s contains substr
}


Otherwise use find:

if (s.find(substr) != std::string::npos) {
    // s contains substr
}

Code Snippets

if (s.contains(substr)) {
    // s contains substr
}
if (s.find(substr) != std::string::npos) {
    // s contains substr
}

Context

Stack Overflow Q#2340281, score: 1194

Revisions (0)

No revisions yet.