溫馨提示×

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

c++
小樊
142
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女