Check if String Contains Substring in C++23

Check if String Contains Substring in C++23

Before C++23, verifying whether a string includes a given substring typically required the find member function. This function searches for the first occurrence of a substring and returns its position. If the substring is not present, it returns npos.

#include <iostream>

int main() {
    std::string text = "Hello world";
    if (text.find("world") != std::string::npos) {
        std::cout << "Found" << std::endl;
    }

    return 0;
}

A frequent mistake when using find is to place its return value directly inside a conditional expression:

#include <iostream>

int main() {
    std::string text = "Hello world";
    if (text.find("Hello")) {
        std::cout << "Found" << std::endl;
    }

    return 0;
}

In this example, the substring "Hello" appears at the start of the string. The find function therefore returns 0. Since 0 evaluates to false in a boolean context, the condition fails and the output statement is skipped.

Since C++23, the standard library introduces the contains member function. This function directly returns a boolean value, making the intent clearer and eliminating the need to compare against npos. The contains function improves readability and reduces the likelihood of logical errors when checking for substrings in modern C++ code.

#include <iostream>

int main() {
    std::string text = "Hello world";
    if (text.contains("world")) {
        std::cout << "Found" << std::endl;
    }

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.