The find() Function
◀ The replace() Function▶ The rfind() Function Amazon
You can use the
find() function to locate the first occurrence of a string, a character array, or a character. How cool is that? If the target is not found, the functions return
string::npos. These functions are useful in a situation where you need to parse a string which contains some sort of delimiter.
int find(const string & s, int pos = 0) const;
int find(const char *cs, int pos = 0) const;
int find(char c, int pos = 0) const;
The first function searches the invoking object for
s starting at index
pos and returns the index where
s is first located. The second one searches invoking object for
cs starting at index
pos and returns the index where
cs is first located.
The third one searches invoking object for
c starting at index
pos and returns the index where
c is first located. As noted before, if the target is not found, all functions return
string::npos.
Here are several examples:
string s = "Ja yo Afu! Yo yo yo!";
string s2 = "yo";
char *s3 = "you";
char c = '!';
unsigned int temp; /* string::npos is a big number */
temp = s.find(s2); /* temp is 3 */
temp = s.find(s2, 4); /* temp is 14 */
temp = s.find(s3); /* temp is string::npos */
temp = s.find(s3, 6); /* temp is string::npos */
temp = s.find(c); /* temp is 9 */
temp = s.find(c, 10); /* temp is 19 */
There are times when you want to locate a string from the end of another string.
Next we’ll discuss this topic!
◀ The replace() Function▶ The rfind() Function