Use s.find("value") != std::string::npos. find returns the index of the first match, or std::string::npos when there is none, and it is case-sensitive. For the start or the end of a string, C++20 has s.starts_with("pre") and s.ends_with(".csv"). s.contains("value") arrives only in C++23.
Until C++23, std::string has no contains: you ask find for the position and compare it with npos. That one comparison is where the bugs live, because a match at index 0 converts to false and npos converts to true. The sections below cover find, prefixes and suffixes, ignoring case without breaking on non-ASCII bytes, every position of a match, checking for any of several words or characters, and whole words with std::regex, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1std::string::find and nposRecommended
text.find(part) returns a std::size_t: the index where part first starts, or std::string::npos when it does not occur. So "contains" is text.find(part) != std::string::npos. It compares bytes exactly, so it is case-sensitive, and it has overloads for a char, a C string and a std::string_view. Wrapping it in a small contains function that takes std::string_view gives you the C++23 member today and reads better at the call site.
#include <iostream> #include <string> #include <string_view> // std::string::contains needs C++23; in C++20 a one-line helper does the job. // string_view parameters accept std::string, literals and views without copies. bool contains(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } int main() { std::string log = "Build failed: 3 errors, 1 warning"; // find returns the index of the first match, or npos when there is none std::cout << log.find("failed") << '\n'; std::cout << std::boolalpha; std::cout << (log.find("failed") != std::string::npos) << '\n'; std::cout << (log.find("passed") != std::string::npos) << '\n'; // It is case-sensitive: "Failed" is not "failed" std::cout << contains(log, "Failed") << '\n'; // A single char works too std::cout << (log.find(':') != std::string::npos) << '\n'; // Keep the position when you need it (if with an initializer, C++17) if (std::size_t pos = log.find("error"); pos != std::string::npos) { std::cout << "error at " << pos << ": " << log.substr(pos) << '\n'; } // npos is the largest std::size_t, not -1 std::cout << std::string::npos << '\n'; // Bug: a match at index 0 converts to false, and npos converts to true if (log.find("Build")) { std::cout << "found Build\n"; } else { std::cout << "missed Build\n"; } if (log.find("zzz")) { std::cout << "found zzz?\n"; } // The empty string is found at index 0 of every string std::cout << log.find("") << ' ' << contains("", "") << '\n'; }
Output
The first line prints 6, the index of failed. The comparisons print true, false for passed, and false for "Failed", because the log says failed. The initializer form keeps the index for later use: error at 16: errors, 1 warning. npos prints as 18446744073709551615, the largest std::size_t, which is why the result belongs in a std::size_t and not an int. Then the bug: if (log.find("Build")) prints missed Build for a string that starts with Build, because index 0 is false, and if (log.find("zzz")) prints found zzz? because npos is not zero. Always compare with npos. The last line, 0 true, shows that the empty string is found at index 0 of every string, even an empty one.
2starts_with and ends_with (C++20)
When the text must be at one end, C++20 says so directly: s.starts_with(prefix) and s.ends_with(suffix) exist on std::string and std::string_view and take a string, a char or a view. Before C++20 the common idiom is s.rfind(prefix, 0) == 0: searching backwards from index 0 tries only that one position. s.find(prefix) == 0 gives the same answer but scans the whole string when the prefix is missing. For a suffix, compare the last characters with compare, after checking the length.
#include <iostream> #include <stdexcept> #include <string> #include <string_view> // Before C++20: check the length first, then compare that many characters bool starts_with(std::string_view s, std::string_view prefix) { return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0; } bool ends_with(std::string_view s, std::string_view suffix) { return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; } int main() { std::string file = "report-2026.csv"; std::cout << std::boolalpha; // C++20: member functions on std::string and std::string_view std::cout << file.starts_with("report") << '\n'; std::cout << file.ends_with(".csv") << '\n'; std::cout << file.ends_with('v') << '\n'; std::cout << file.ends_with(".CSV") << '\n'; // case-sensitive // The classic pre-C++20 idiom: rfind(prefix, 0) only tries index 0 std::cout << (file.rfind("report", 0) == 0) << '\n'; // The helpers above, for older compilers std::cout << starts_with(file, "rep") << ' ' << ends_with(file, "2026.csv") << '\n'; std::cout << ends_with("csv", "file.csv") << '\n'; // Without the size check, size() - suffix.size() wraps around and throws try { std::string s = "csv"; std::string suffix = "file.csv"; std::cout << s.compare(s.size() - suffix.size(), suffix.size(), suffix) << '\n'; } catch (const std::out_of_range& e) { std::cout << "out_of_range: " << e.what() << '\n'; } // Starts with a prefix? Then convert the rest to an int std::string arg = "--port=8080"; constexpr std::string_view prefix = "--port="; if (arg.starts_with(prefix)) { int port = std::stoi(arg.substr(prefix.size())); std::cout << "port " << port << ", next " << port + 1 << '\n'; } }
Output
The C++20 members print true three times, then false for .CSV: they are case-sensitive like find. The rfind idiom prints true, and the helpers print true true, then false for a suffix longer than the string. That length check is not optional: without it, s.size() - suffix.size() is 3 - 8 in unsigned arithmetic, which wraps to a huge index, and compare throws out_of_range: basic_string::compare: __pos (which is 18446744073709551611) > this->size() (which is 3). The last block is the second half of a popular question, "starts with, then convert the rest to an int": substr(prefix.size()) drops the prefix and std::stoi reads port 8080, next 8081. More on that conversion in converting a string to an int.
3Case-insensitive search
The standard library has no case-insensitive find. The usual answer is std::search with a predicate that compares two characters through std::tolower; it returns an iterator to the first match, or the end iterator. C++20's std::ranges::search does the same with a projection on each side and no helper function. Lowercasing copies of both strings also works, at the cost of two allocations. Whichever you pick, cast each char to unsigned char before std::tolower: char is signed on most platforms, and passing a negative value is undefined behaviour.
#include <algorithm> #include <cctype> #include <iostream> #include <string> #include <string_view> // Compare two chars ignoring ASCII case. The unsigned char cast matters: // std::tolower on a negative char (any byte >= 0x80) is undefined behaviour bool iequal(char a, char b) { return std::tolower(static_cast<unsigned char>(a)) == std::tolower(static_cast<unsigned char>(b)); } // Index of the first case-insensitive match, or npos std::size_t ifind(std::string_view text, std::string_view part) { auto it = std::search(text.begin(), text.end(), part.begin(), part.end(), iequal); if (it == text.end() && !part.empty()) { return std::string_view::npos; } return static_cast<std::size_t>(it - text.begin()); } bool icontains(std::string_view text, std::string_view part) { return ifind(text, part) != std::string_view::npos; } std::string to_lower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); return s; } int main() { std::string title = "Learning C++ with CompileBytes"; std::cout << std::boolalpha; std::cout << (title.find("compilebytes") != std::string::npos) << '\n'; std::cout << icontains(title, "compilebytes") << '\n'; std::cout << ifind(title, "WITH") << '\n'; // C++20 ranges: project both sides through tolower, no helper needed auto lower = [](unsigned char c) { return std::tolower(c); }; std::string_view word = "LEARNING"; auto hit = std::ranges::search(title, word, {}, lower, lower); std::cout << !hit.empty() << '\n'; // Lowercase copies work too, at the cost of two new strings std::string lowered = to_lower(title); std::cout << (lowered.find(to_lower("C++ WITH")) != std::string::npos) << '\n'; // tolower only knows ASCII: UTF-8 "É" and "é" are different bytes std::cout << icontains("CAFÉ MENU", "café") << '\n'; std::cout << icontains("CAFÉ MENU", "caf") << '\n'; }
Output
Plain find prints false for compilebytes, while icontains prints true and ifind puts WITH at 13. The ranges version and the lowercased copies both print true. The last two lines are the limit of all three: std::tolower works on single bytes, and in UTF-8 É and é are two-byte sequences that differ, so "café" is not found in "CAFÉ MENU" (false) while the ASCII caf is (true). Case-folding beyond ASCII needs a Unicode library such as ICU. For lowercasing on its own, see converting a string to lowercase.
4Every match, the last match, and counting
find takes a second argument, the index to start from, so a loop that restarts after each match finds every one. Move on by the length of the match to count non-overlapping matches, or by one character to count overlapping ones. rfind searches from the end for the last match. For long needles in long texts, C++17 added searchers to <functional>: std::search with a std::boyer_moore_horspool_searcher skips ahead instead of trying every position.
#include <algorithm> #include <functional> #include <iostream> #include <string> #include <string_view> #include <vector> // Every index where part occurs. overlap = true restarts one char after a match std::vector<std::size_t> find_all(std::string_view text, std::string_view part, bool overlap = false) { std::vector<std::size_t> positions; if (part.empty()) { return positions; // "" matches everywhere: the loop would never end } std::size_t step = overlap ? 1 : part.size(); for (std::size_t pos = text.find(part); pos != std::string_view::npos; pos = text.find(part, pos + step)) { positions.push_back(pos); } return positions; } int main() { std::string text = "the cat sat on the mat with the hat"; std::vector<std::size_t> hits = find_all(text, "the"); std::cout << "\"the\" at"; for (std::size_t p : hits) { std::cout << ' ' << p; } std::cout << ", count " << hits.size() << '\n'; // rfind searches backwards: the last match std::cout << "first " << text.find("the") << ", last " << text.rfind("the") << '\n'; // The second argument of find is where to start looking std::cout << "after 1: " << text.find("the", 1) << '\n'; // Overlapping matches count only when the search moves on by one std::cout << find_all("aaaa", "aa").size() << ' ' << find_all("aaaa", "aa", true).size() << '\n'; // C++17 searchers: Boyer-Moore-Horspool skips ahead, which pays off // for long needles in long texts std::string needle = "hat"; std::boyer_moore_horspool_searcher searcher(needle.begin(), needle.end()); auto it = std::search(text.begin(), text.end(), searcher); std::cout << "searcher: " << (it - text.begin()) << '\n'; }
Output
The loop prints "the" at 0 15 28, count 3, and find and rfind agree on the ends: first 0, last 28. Starting at index 1 skips the first match and gives after 1: 15. aa occurs 2 times in aaaa without overlap and 3 times with it, so decide which one your count means. The empty-needle guard matters: find("", pos) returns pos, so with a step of zero the loop would never end. The searcher finds hat at 32, the same answer as find; it only pays off on large inputs, so measure before switching.
5Any of several words or characters
To test a string against a list of words, put the find check in a lambda and hand it to std::ranges::any_of (at least one), all_of (every one) or find_if (which one). For single characters, find_first_of(chars) returns the index of the first character that is in the set, and find_first_not_of(chars) the first one that is not. Their names are close to find, and mixing them up is a common bug.
#include <algorithm> #include <array> #include <iostream> #include <string> #include <string_view> int main() { std::string comment = "Great post, but the spam filter flagged my link"; std::array<std::string_view, 3> banned{"spam", "scam", "casino"}; std::array<std::string_view, 2> required{"post", "link"}; auto in_comment = [&](std::string_view word) { return comment.find(word) != std::string::npos; }; std::cout << std::boolalpha; // Does it contain ANY of the words? ALL of them? std::cout << std::ranges::any_of(banned, in_comment) << '\n'; std::cout << std::ranges::all_of(required, in_comment) << '\n'; // Which one matched? auto hit = std::ranges::find_if(banned, in_comment); std::cout << (hit != banned.end() ? *hit : "none") << '\n'; // Any of a set of CHARACTERS: find_first_of std::string file_name = "report:2026?.txt"; std::string_view invalid = "<>:\"|?*"; std::cout << file_name.find_first_of(invalid) << '\n'; std::cout << (std::string_view("report-2026.txt").find_first_of(invalid) == std::string_view::npos) << '\n'; // Anything that is NOT a digit? find_first_not_of std::string pin = "12a4"; std::cout << pin.find_first_not_of("0123456789") << '\n'; // Trap: find_first_of looks for any one of the characters, not the word std::string greeting = "hello"; std::cout << greeting.find_first_of("world") << ' ' << (greeting.find("world") == std::string::npos) << '\n'; }
Output
Prints true (the comment has spam), true (it has both post and link) and spam, the first banned word that matched. In the file name, find_first_of finds the : at 6, and report-2026.txt has none of the characters (true). find_first_not_of finds the a in 12a4 at 2, so the PIN is not all digits. The last line is the trap: "hello".find_first_of("world") returns 2, the first l, although hello does not contain world (true for npos). To look for a whole element in a container rather than inside a string, see checking if a vector contains an element.
6Whole words and patterns with std::regex
find("cat") also matches category and concatenated. When you mean the whole word, or the thing to look for is a pattern rather than fixed text, use std::regex_search from <regex>. \b marks a word boundary, std::regex::icase ignores case, and a raw string literal R"(...)" saves doubling every backslash. Use regex_search, not regex_match: the second one succeeds only when the pattern matches the entire string. The standard library has no regex escape function, so text from a user needs one before it goes into a pattern.
#include <iostream> #include <regex> #include <string> // std::regex has no escape function: put a backslash before each special char std::string regex_escape(const std::string& s) { static const std::regex special(R"([.^$|()\[\]{}*+?\\])"); return std::regex_replace(s, special, R"(\$&)"); } int main() { std::string sentence = "The category is concatenated with cat_id"; std::cout << std::boolalpha; // find matches inside words std::cout << (sentence.find("cat") != std::string::npos) << '\n'; // \b is a word boundary: "cat" as a whole word only const std::regex whole_cat(R"(\bcat\b)", std::regex::icase); std::cout << std::regex_search(sentence, whole_cat) << '\n'; std::cout << std::regex_search("I have a Cat.", whole_cat) << '\n'; // A pattern instead of fixed text: does it contain an order number? std::string ref = "Ref: order #A-10427 shipped"; std::smatch m; if (std::regex_search(ref, m, std::regex(R"(#[A-Z]-\d+)"))) { std::cout << m.str() << " at " << m.position() << '\n'; } // regex_match must match the WHOLE string; regex_search finds a part std::cout << std::regex_match(ref, std::regex("order")) << ' ' << std::regex_search(ref, std::regex("order")) << '\n'; // User input is not a pattern. "C++" compiles, but it means "one or more C", // so it matches text with no "C++" in it std::string langs = "C, Go and Rust"; std::cout << std::regex_search(langs, std::regex("C++")) << '\n'; std::cout << std::regex_search(langs, std::regex(regex_escape("C++"))) << '\n'; // Other input is not a valid pattern at all try { std::regex smiley(":)"); } catch (const std::regex_error& e) { std::cout << "regex_error: " << e.what() << '\n'; } std::string pattern = regex_escape("C++ (beta)"); std::cout << pattern << '\n'; std::cout << std::regex_search("Try C++ (beta) today", std::regex(pattern)) << '\n'; }
Output
find prints true because cat sits inside category, while the whole-word pattern prints false for that sentence (the underscore in cat_id is a word character, so it is no boundary) and true for I have a Cat.. The order-number pattern finds #A-10427 at 11, and false true shows regex_match failing where regex_search succeeds. Unescaped, "C++" is accepted by GCC's library but means one or more C, so it prints true for C, Go and Rust; escaped, it prints false. Other input does not compile as a pattern at all: ":)" throws regex_error: Mismatched '(' and ')' in regular expression. The escape helper turns C++ (beta) into C\+\+ \(beta\), which matches (true). Building a std::regex is slow, so make it once (a static const, as in the helper) and reuse it.
7Which should you use?
| Method | Case | Standard | Best for |
|---|---|---|---|
| s.find(x) != std::string::npos | Sensitive | Any | The default check, and the position |
| s.contains(x) | Sensitive | C++23 | Same check, once your compiler is on C++23 |
| s.starts_with(x) / s.ends_with(x) | Sensitive | C++20 | Prefixes and suffixes |
| s.rfind(x, 0) == 0 | Sensitive | Any | A prefix before C++20 |
| std::search(..., iequal) | Ignored (ASCII) | Any | Case-insensitive search; ranges::search in C++20 |
| ranges::any_of(words, ...) | Your choice | C++20 | Any or all of a few words |
| s.find_first_of(chars) | Sensitive | Any | Any of a set of characters |
| std::regex_search(s, re) | std::regex::icase | C++11 | Whole words, patterns; slow to build |
| if (s.find(x)) | Sensitive | Any | Never: index 0 is false, npos is true |
Frequently asked questions
Does std::string have a contains() function?
Only from C++23, where std::string and std::string_view get contains, which takes a string, a view or a char. In C++20 and earlier write s.find(x) != std::string::npos, or wrap it in a small bool contains(std::string_view text, std::string_view part) helper. C++20 already has starts_with and ends_with, so prefix and suffix checks need no workaround.
Why does if (s.find("x")) give the wrong answer?
find returns an index, not a bool. A match at the very start returns 0, which converts to false, and a missing substring returns std::string::npos, the largest std::size_t, which converts to true. So the condition is backwards in exactly the two cases that matter. Compare with npos every time: if (s.find("x") != std::string::npos).
What is std::string::npos?
A static const std::size_t equal to -1 converted to std::size_t, which is the largest value the type holds: 18446744073709551615 on a 64-bit system. The search functions return it to mean "not found", and functions like substr read it as "to the end of the string". Store a find result in std::size_t (or auto), not int, so the comparison with npos stays exact.
How do I check if a char* or C string contains a substring?
In C-style code, std::strstr(text, part) from <cstring> returns a pointer to the first match or a null pointer, so the check is std::strstr(text, part) != nullptr. In C++ code, wrap the pointer in a std::string_view and use the same find: std::string_view(text).find(part) != std::string_view::npos. That works without copying, and both need a null-terminated string.
How do I check if a string contains a substring, ignoring case?
Use std::search with a predicate that compares std::tolower(static_cast<unsigned char>(a)) with the same for b, or in C++20 std::ranges::search(text, part, {}, lower, lower) with a lower lambda that takes an unsigned char. The cast matters, because std::tolower on a negative char is undefined behaviour. Both only fold ASCII letters; matching "É" with "é" in UTF-8 needs a Unicode library such as ICU.
Is std::string::find fast enough?
For everyday strings, yes: it is a simple scan with no setup cost, and GCC's library uses memchr to jump to each candidate first character. Its worst case grows with the text length times the needle length, though. For long needles searched in long texts, C++17's std::boyer_moore_searcher or std::boyer_moore_horspool_searcher with std::search can skip ahead, and building the searcher once lets you reuse it on many texts. Measure before switching.