0
点赞
收藏
分享

微信扫一扫

C++ 89 之 string查找和替换

彪悍的鼹鼠 2024-06-22 阅读 43
#include <iostream>
#include <string>
using namespace std;

int main()
{
// int find(const string& str, int pos = 0) const; //查找str第一次出现位置,从pos开始查找
// int find(const char* s, int pos = 0) const;  //查找s第一次出现位置,从pos开始查找
// int find(const char c, int pos = 0) const;  //查找字符c第一次出现位置
// int rfind(const string& str, int pos = npos) const;//查找str最后一次位置,从pos开始查找
// int rfind(const char* s, int pos = npos) const;//查找s最后一次出现位置,从pos开始查找
// int rfind(const char c, int pos = 0) const; //查找字符c最后一次出现位置
// string& replace(int pos, int n, const string& str); //替换从pos开始n个字符为字符串str
// string& replace(int pos, int n, const char* s); //替换从pos开始的n个字符为字符串s


    //int find(const string& str, int pos = 0) const; //查找str第一次出现位置,从pos开始查找
    string str1 = "abcdefghijk";
    string str2 = "cd";
    int pos1 = str1.find(str2,3);  // 从第三个位置开始找cd第一次出现的位置  rfind() r代表从右往左
    if(pos1 == -1){
        cout << "未找到" << endl;
    }
    else{
        cout << pos1 << endl;
    }

    //int find(const char* s, int pos = 0) const;  //查找s第一次出现位置,从pos开始查找
    int pos2 = str1.find("d");  // 从0开始找cd第一次出现的位置
    if(pos2 == -1){
        cout << "未找到" << endl;
    }
    else{
        cout << pos2 << endl;
    }

    //  int find(const char c, int pos = 0) const;  //查找字符c第一次出现位置
    int pos3 = str1.rfind('d');  // 从0开始找cd第一次出现的位置
    if(pos3 == -1){
        cout << "未找到" << endl;
    }
    else{
        cout << pos3 << endl;
    }



    return 0;
}

 

举报

相关推荐

0 条评论