温馨提示×

C++ string rfind有哪些实用技巧

c++
小樊
94
2024-07-19 03:09:44
栏目: 编程语言

  1. 查找指定字符或子串最后一次出现的位置: 可以使用rfind函数来查找指定字符或子串在字符串中最后一次出现的位置。例如:
std::string str = "hello world";
size_t pos = str.rfind("o");
if (pos != std::string::npos) {
    std::cout << "Last occurrence of 'o' is at position " << pos << std::endl;
}
  1. 从指定位置开始查找: 可以指定从字符串的某个位置开始查找指定字符或子串的最后一次出现位置。例如:
std::string str = "hello world";
size_t pos = str.rfind("o", 5);
if (pos != std::string::npos) {
    std::cout << "Last occurrence of 'o' before position 5 is at position " << pos << std::endl;
}
  1. 逆向查找多个字符或子串: 可以结合rfind和substr函数来逆向查找多个字符或子串。例如:
std::string str = "hello world";
size_t pos = str.rfind("world");
if (pos != std::string::npos) {
    std::string sub = str.substr(pos, 5);
    std::cout << "Substring found: " << sub << std::endl;
}
  1. 使用循环逆向查找多个字符或子串: 如果需要查找字符串中所有符合条件的子串位置,可以使用循环结合rfind函数。例如:
std::string str = "hello world hello";
size_t pos = str.rfind("hello");
while (pos != std::string::npos) {
    std::cout << "Last occurrence of 'hello' is at position " << pos << std::endl;
    pos = str.rfind("hello", pos - 1);
}

0