The string class provides several other functions that you can invoke on strings. The find function is like the opposite the [] operator. Instead of taking an index and extracting the character at that index, find takes a character and finds the index where that character appears.
This example finds the index of the letter 'a' in the string. In this case, the letter appears three times, so it is not obvious what find should do. According to the documentation, it returns the index of the first appearance, so the result is 1. If the given letter does not appear in the string, find a very large integer. We can test whether find found a given letter by checking to see if it equals the constant defined by string::npos .
You should remember from SectionΒ 5.4 that there can be more than one function with the same name, as long as they take a different number of parameters or different types. In this case, C++ knows which version of find to invoke by looking at the type of the argument we provide.
int main() {
---
string city = "New Baltimore";
---
string city = "New Baltimore" #paired
---
size_t index = city.find('B');
---
size_t index = city.find(B); #paired
---
size_t index = city.find('b'); #paired
---
cout << index << endl;
}
string sentence = "Most seas are rough but this sea is so calm!";
string target = "sea";
size_t index = sentence.find(target);
cout << "Index to find sea is " << index << endl;