find函数用于在string中查找子串,返回子串第一个字符的下标位置。 如果查找失败,则返回 string::npos。
string str = "hello world!";string substr = "world";size_t pos = str.find(substr);if (pos != string::npos) { cout << “发现位置:” << pos << endl;}
2. rfind
rfind函数与find函数类似,不同的是它是从字符串开始寻找末尾的子串。 如果查找失败,则返回 string::npos。
1. find
string str = “hello world!”;
字符串 substr = “l”;
size_t pos = str.rfind(substr);
如果 (pos != string::npos) {
cout << "找到位置:" << pos << endl;
}
3. find_first_of
find_first_of函数用于查找字符串中匹配子串中任意字符的第一个位置,返回子串第一个字符的下标位置。 如果查找失败,则返回 string::npos。
string str = "hello world!";
// 找到第一次出现的 'o' 或 'w'。
字符串 substr = "ow";
size_t pos = str.find_first_of(substr);
如果 (pos != string::npos) {
cout << "找到位置:" << pos << endl;
}
4. find_last_of
find_last_of函数与find_first_of函数类似,不同之处在于它是从字符串末尾开始查找第一个匹配子串s位置的任意字符。 如果查找失败,则返回 string::npos。
string str = “hello world!”;
字符串 substr = “ow”;
size_t pos = str.find_last_of(substr);
如果 (pos != string::npos) {
cout << "找到位置:" << pos << endl;
}
find_first_not_of()
find_first_not_of()方法查找字符串中第一个不属于指定字符集的字符,并返回该字符的位置 特点。
size_t find_first_not_of (const string& str, size_t pos = 0) const noexcept;
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
size_t find_first_not_of (const char* s, size_t pos = 0) const;
size_t find_first_not_of (char c, size_t pos = 0) const noexcept;
参数说明:
函数返回值:
- 如果找到指定字符集之外的字符,则返回该字符在字符串中的位置。
- 如果没有找到匹配的字符,则返回string::npos。
find_last_not_of()
find_last_not_of()方法查找字符串中最后一个不属于指定字符集的字符,并返回该字符的位置 .
size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept;
size_t find_last_not_of (const char* s, size_t pos, size_t n) const;
size_t find_last_not_of (const char* s, size_t pos = npos) const;
size_t find_last_not_of (char c, size_t pos = npos) const noexcept;
参数说明:
- str:要查找的字符串 .
- s:要查找的字符数组。
- n:求字符数组的长度。
- pos: 寻找结束位置。
- c:要查找的字符。
函数返回值:
- 如果找到指定字符集之外的字符,则在字符串中返回该字符 中的位置。
- 如果没有找到匹配的字符,则返回string::npos。