FIND()
This member of the std::string class is used to locate the first occurrence of a substring or character within a string. It searches from left to right, starting at a specified index (default is 0), and returns the position (as a size_t index) where the match is found. If the substring or character does not exist in the string, it returns the special constant std::string::npos. This makes it useful for string parsing, validation, or extracting specific parts of text.
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (char c, size_t pos = 0) const;
* str → the substring to search for.
* s → C-string (null-terminated char array).
* n → number of characters from s to use.
* c → single character to search for.
* pos → starting index for the search (default is 0).
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "banana";
// find the first occurrence of "na"
size_t first = text.find("na"); // index 2 - left-to-right search
// find the last occurrence of "na"
size_t last = text.rfind("na"); // index 4 - right-to-left search
cout << "First: " << first << endl;
cout << "Last: " << last << endl;
return 0;
}
Last updated