How to Use find() in String in C++: Syntax and Examples
In C++, use the
find() method of the std::string class to search for a substring or character. It returns the position index of the first match or std::string::npos if not found.Syntax
The find() method is called on a std::string object and has several overloads. The most common form is:
size_t find(const std::string& str, size_t pos = 0) const;- Finds the substringstrstarting from indexpos.size_t find(char ch, size_t pos = 0) const;- Finds the characterchstarting from indexpos.
The method returns the index of the first occurrence or std::string::npos if not found.
cpp
size_t find(const std::string& str, size_t pos = 0) const; size_t find(char ch, size_t pos = 0) const;
Example
This example shows how to find a substring and a character in a string. It prints the found positions or a message if not found.
cpp
#include <iostream> #include <string> int main() { std::string text = "Hello, world!"; // Find substring "world" size_t pos1 = text.find("world"); if (pos1 != std::string::npos) { std::cout << "Found 'world' at position: " << pos1 << '\n'; } else { std::cout << "'world' not found" << '\n'; } // Find character 'o' size_t pos2 = text.find('o'); if (pos2 != std::string::npos) { std::cout << "Found 'o' at position: " << pos2 << '\n'; } else { std::cout << "'o' not found" << '\n'; } return 0; }
Output
Found 'world' at position: 7
Found 'o' at position: 4
Common Pitfalls
Common mistakes when using find() include:
- Not checking if the result equals
std::string::nposbefore using the position. - Assuming
find()returns -1 when not found (it returnsstd::string::npos, which is a large unsigned number). - Using the found position without verifying it is valid, which can cause bugs.
Always compare the result with std::string::npos before using it.
cpp
#include <iostream> #include <string> int main() { std::string text = "example"; // Wrong: assuming -1 means not found auto pos_wrong = text.find("test"); if (pos_wrong == -1) { // This check is incorrect std::cout << "Not found (wrong check)" << '\n'; } // Right: compare with std::string::npos size_t pos_right = text.find("test"); if (pos_right == std::string::npos) { std::cout << "Not found (correct check)" << '\n'; } return 0; }
Output
Not found (correct check)
Quick Reference
Summary tips for using find() in C++ strings:
- Use
find()to locate substrings or characters. - Check if the result is
std::string::nposto know if not found. - Start searching from a specific position by passing the
posargument. find()returns the first occurrence index.
Key Takeaways
Use std::string::find() to search for substrings or characters in a string.
Always check if the returned position equals std::string::npos before using it.
The find() method returns the index of the first match or npos if not found.
You can specify the starting position for the search with an optional argument.
Do not assume find() returns -1; it returns std::string::npos, an unsigned value.