温馨提示×

c++ string类的查找功能如何使用

c++
小樊
82
2024-08-28 02:32:57
栏目: 编程语言

C++中的std::string类提供了几种查找功能,包括find(), rfind(), find_first_of(), find_last_of()等。下面是这些函数的简单介绍和示例:

  1. size_t find(const std::string& str, size_t pos = 0) const noexcept;

    在当前字符串中从位置pos开始查找子字符串str第一次出现的位置。如果找不到则返回std::string::npos

    #include<iostream>
    #include<string>
    
    int main() {
        std::string s("hello world");
        std::string sub("world");
        size_t pos = s.find(sub);
        if (pos != std::string::npos) {
            std::cout << "Found at position: "<< pos<< std::endl;
        } else {
            std::cout << "Not found"<< std::endl;
        }
        return 0;
    }
    
  2. size_t rfind(const std::string& str, size_t pos = npos) const noexcept;

    在当前字符串中从位置pos开始查找子字符串str最后一次出现的位置。如果找不到则返回std::string::npos

    #include<iostream>
    #include<string>
    
    int main() {
        std::string s("hello world world");
        std::string sub("world");
        size_t pos = s.rfind(sub);
        if (pos != std::string::npos) {
            std::cout << "Found at position: "<< pos<< std::endl;
        } else {
            std::cout << "Not found"<< std::endl;
        }
        return 0;
    }
    
  3. size_t find_first_of(const std::string& str, size_t pos = 0) const noexcept;

    在当前字符串中从位置pos开始查找str中任意字符第一次出现的位置。如果找不到则返回std::string::npos

    #include<iostream>
    #include<string>
    
    int main() {
        std::string s("hello world");
        std::string chars("wro");
        size_t pos = s.find_first_of(chars);
        if (pos != std::string::npos) {
            std::cout << "Found at position: "<< pos<< std::endl;
        } else {
            std::cout << "Not found"<< std::endl;
        }
        return 0;
    }
    
  4. size_t find_last_of(const std::string& str, size_t pos = npos) const noexcept;

    在当前字符串中从位置pos开始查找str中任意字符最后一次出现的位置。如果找不到则返回std::string::npos

    #include<iostream>
    #include<string>
    
    int main() {
        std::string s("hello world");
        std::string chars("wro");
        size_t pos = s.find_last_of(chars);
        if (pos != std::string::npos) {
            std::cout << "Found at position: "<< pos<< std::endl;
        } else {
            std::cout << "Not found"<< std::endl;
        }
        return 0;
    }
    

这些函数可以根据需要进行组合使用,以实现更复杂的查找功能。注意,当使用std::string::npos作为参数时,表示从字符串的末尾开始查找。

0