String Contains

How to Check if a String Contains a Substring in C++

Learn how to check if a C++ string contains a substring using find(), the C++23 contains() member and strstr() for C-style strings, with examples.

On this page
  1. The short answer
  2. Check with find()
  3. Use contains() in C++23
  4. Check a C-style string with strstr()
  5. Common mistakes
  6. Ignore case
  7. Other options
  8. Summary

The short answer

This guide covers the C string contains check that most programs need, in its C++ forms. To check whether a std::string contains a substring, call find() and compare its result with std::string::npos. If your compiler supports C++23, contains() does the same check and returns a bool, so the if statement is shorter.

if (sentence.find(word) != std::string::npos) {
    // word appears somewhere in sentence
}

A substring check is not the same as an equality check. To test whether two strings match exactly, see how to compare two strings in c.

Check with find()

find() scans the string from the start. It returns the index where the substring first begins, counting from 0. If the substring is not there, it returns std::string::npos, a special value that means no position was found.

#include <iostream>
#include <string>

int main() {
    std::string sentence = "The quick brown fox jumps over the lazy dog";
    std::string word = "brown";

    std::size_t position = sentence.find(word);

    if (position != std::string::npos) {
        std::cout << "Found at index " << position << '\n';
    } else {
        std::cout << "Not found\n";
    }
}

The program prints Found at index 10. The b in “brown” is the eleventh character, so its index is 10.

The full set of find() arguments, including the starting position, is described in our guide to c string find.

Use contains() in C++23

C++23 added a contains() member function to std::string and std::string_view. It returns true or false, which reads more directly than comparing with npos.

#include <iostream>
#include <string>

int main() {
    std::string sentence = "The quick brown fox jumps over the lazy dog";

    if (sentence.contains("lazy")) {
        std::cout << "Found\n";
    }
}

To build it, turn on C++23, for example with g++ -std=c++23 main.cpp. Your compiler and standard library must support C++23. If they do not, use find(), which has been part of the standard library for a long time.

Check a C-style string with strstr()

A C-style string is a char array or pointer that ends with a null character. std::string is not involved in this case. The usual function is std::strstr from <cstring>. It returns a pointer to the first match, or nullptr if there is none.

#include <cstring>
#include <iostream>

int main() {
    const char* sentence = "The quick brown fox";
    const char* word = "quick";

    if (std::strstr(sentence, word) != nullptr) {
        std::cout << "Found\n";
    }
}

Both arguments must end in a null character. If they do not, the function can read past the end of the array. For more on how this function behaves, see the article What does strstr() do in C?

Common mistakes

Using find() as a true or false value. find() returns an index, not a yes-or-no answer. A match at index 0 becomes false when converted to a bool, and a miss becomes true, because npos is not zero. Compare with std::string::npos every time.

Expecting a case-insensitive match. The search is case-sensitive, so “Brown” does not match “brown”.

Passing a std::string to strstr. std::strstr takes C-style strings, so a std::string will not compile in that position. Call c_str() to get a const char* from it.

Ignore case

To ignore case, convert both strings to lowercase first, then search. This example uses std::transform from <algorithm>:

#include <algorithm>
#include <cctype>
#include <string>

std::string to_lower(std::string text) {
    std::transform(text.begin(), text.end(), text.begin(),
                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
    return text;
}

bool contains_ignore_case(const std::string& text, const std::string& word) {
    return to_lower(text).find(to_lower(word)) != std::string::npos;
}

The cast to unsigned char is needed because passing a negative char value to std::tolower is undefined behavior. For plain ASCII text, this approach is enough. Other character sets need more careful handling. Walking through each character to change its case uses the same idea as how to iterate through a string in c.

Other options

  • Single characters. sentence.find('q') searches for one character and returns its index.
  • Starting position. sentence.find(word, 5) starts the search at index 5, which skips the first five characters.
  • Prefix and suffix. In C++20, starts_with() and ends_with() check the start or end of a string. They read more clearly than checking whether find() returns 0.
  • string_view. std::string_view, from C++17, also has find(). It works on text without copying it.
  • Other member functions. std::string has several more member functions, which are covered in c string methods.

Summary

  • Use find() and compare the result with std::string::npos. This works in any C++ version that has std::string.
  • Use contains() in C++23 for a shorter check.
  • Use std::strstr for C-style strings, and check that both strings end in a null character.
  • Searches are case-sensitive unless you convert the text first.

Keep exploring

Guides from other topics

All topics →

How to Stringify a Macro in C++

Learn how the # operator turns a C++ macro argument into a string literal, with examples, the two-level trick for expanded macros and common pitfalls.

Macros 3 min read