How to Find Substring in C++: Simple Guide with Examples
In C++, you can find a substring inside a string using the
std::string::find method. It returns the position of the first occurrence of the substring or std::string::npos if not found.Syntax
The basic syntax to find a substring in C++ is:
size_t pos = str.find(substring);Here:
stris the main string you want to search in.substringis the string you want to find.poswill hold the index wheresubstringstarts instr.- If
substringis not found,poswill bestd::string::npos, a special value.
cpp
size_t pos = str.find(substring);Example
This example shows how to find a substring and check if it exists in the main string.
cpp
#include <iostream> #include <string> int main() { std::string text = "Hello, welcome to C++ programming!"; std::string word = "welcome"; size_t position = text.find(word); if (position != std::string::npos) { std::cout << "Found '" << word << "' at position " << position << ".\n"; } else { std::cout << "Substring not found.\n"; } return 0; }
Output
Found 'welcome' at position 7.
Common Pitfalls
Common mistakes when finding substrings in C++ include:
- Not checking if the result is
std::string::nposbefore using the position. - Confusing
nposwith-1.nposis an unsigned value and should be compared using!= std::string::npos. - Using
findon empty strings or searching for empty substrings without understanding the behavior.
cpp
#include <iostream> #include <string> int main() { std::string text = "example"; std::string search = "z"; // Wrong: Not checking for npos size_t pos = text.find(search); // Using pos directly without check can cause bugs if (pos != std::string::npos) { std::cout << "Found at " << pos << "\n"; } else { std::cout << "Not found" << std::endl; } return 0; }
Output
Not found
Quick Reference
Summary tips for using std::string::find:
- Returns the index of the first match or
std::string::nposif not found. - Use
if (pos != std::string::npos)to check if found. - Can specify a starting position:
str.find(substring, start_pos). - Works with
std::stringand C-style strings.
Key Takeaways
Use std::string::find to locate a substring's position in a string.
Always check if the result is std::string::npos before using the position.
The find method returns the first occurrence index or npos if not found.
You can specify a starting index to search from in the find method.
Avoid using the position without verifying it is not npos to prevent bugs.