In C++, std::string::find() searches a string for a word or one character. It returns the index where the first match starts. Counting starts at 0, so the first character is index 0.
You can search from the beginning, or start later by passing a position. If the text is not there, the result is std::string::npos, not an error and not -1. Include <string>.
Syntax
Call find on the string you already have. Start with these two lines.
C++
text.find("C++");
text.find("C++", 4);
Call
What it does
text.find("C++")
Looks through the whole string, from the first character.
text.find("C++", 4)
Skips everything before index 4, then looks. Use this only when you want a later match.
For one character, use single quotes: text.find('C').
#include <iostream>
#include <string>
int main() {
std::string email = "[email protected]";
std::size_t at = email.find('@');
std::size_t hash = email.find('#');
std::cout << "At sign index: " << at << '\n';
if (hash == std::string::npos) {
std::cout << "No hash symbol.\n";
}
return 0;
}
Output
At sign index: 4
No hash symbol.
How It Works
find('@') finds the character at index 4.
find('#') returns npos.
Handle missing matches with an npos check.
Example 3 — Start Position
Pass pos to find the next match.
C++
#include <iostream>
#include <string>
int main() {
std::string word = "banana";
std::size_t first = word.find("na");
std::size_t second = word.find("na", first + 1);
std::cout << "First: " << first << '\n';
std::cout << "Second: " << second << '\n';
return 0;
}
Output
First: 2
Second: 4
How It Works
First "na" starts at index 2.
Second call starts at first + 1.
Next match is at index 4.
Frequently Asked Questions
In C++, std::string::find() looks through a string for a word or one character. It returns the index where the first match starts, counting from 0. If the text is not there, it returns std::string::npos.
str is the text to search for. pos is optional and sets the index where the search starts. The default is 0, the beginning of the string.
The index of the first match, or std::string::npos when the text is not found. Compare the result with npos before you use the index.
Yes. Uppercase and lowercase letters must match.
Use if (text.find("C++") != std::string::npos). The text is present when the index is not npos.
find() returns an index, not true or false. A match at index 0 is valid, but an if statement treats 0 as false. Use pos != std::string::npos instead.