天天看点

C++ 字符串查找函数

1. find

find函数用于在string中查找一个子串,返回子串的首个字符所在的下标位置。如果查找失败,则返回string::npos。

string str = "hello world!";
string substr = "world";
size_t pos = str.find(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

2. rfind

rfind 函数与 find 函数类似,不同的是它从字符串的末尾开始查找子串。如果查找失败,则返回string::npos。

string str = "hello world!";
string substr = "l";
size_t pos = str.rfind(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

3. find_first_of

find_first_of函数用于查找字符串中第一个匹配子串中的任意字符的位置,返回子串的首个字符所在的下标位置。如果查找失败,则返回string::npos。

string str = "hello world!";
// 查找 'o' 或者 'w' 的第一个出现的位置。
string substr = "ow";	
size_t pos = str.find_first_of(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

4. find_last_of

find_last_of函数与find_first_of函数类似,不同的是它从字符串的末尾开始查找第一个匹配子串中的任意字符的位置。如果查找失败,则返回string::npos。

string str = "hello world!";
string substr = "ow";
size_t pos = str.find_last_of(substr);
if (pos != string::npos) {
    cout << "Found at position: " << 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;           

参数说明:

  • str:要查找的字符串。
  • s:要查找的字符数组。
  • n:查找字符数组的长度。
  • pos:查找起始位置。
  • c:要查找的字符。

函数返回值:

  • 如果找到了指定字符集之外的字符,则返回该字符在字符串中的位置。
  • 如果没有找到符合条件的字符,则返回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。

继续阅读