• STL容器之string查找和替换


    1.查找和替换

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    using namespace std;
    /*
    查找和替换
    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* s, int pos, int n) const;  //从pos位置查找s的前n个字符第一次位置
    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* s, int pos, int n) const;//从pos查找s的前n个字符最后一次位置
    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
    */
    void test01()
    {
        string s = "abcdefg";
        //查找
        int pos = s.find("bcf");  // 查不到返回-1
        cout << pos << endl;    //-1
        int pos2 = s.rfind("bc");   //虽然从后往前查找 返回的还是正常的索引顺序 即rfind和find查找顺序相反 结果相同
        cout << pos2 << endl;   //1
    
        //替换
        string s2 = "hello";
        s2.replace(1, 2, "2222"); //string& replace(int pos, int n, const string& str); 
                                  //替换从pos开始n个字符为字符串str,并非是只取str的n个字符串替换,而是整个str替换原字符串pos后的n个位置的这一段字符串
        cout << s2 << endl;     //h 2222(被替换的el) lo  -> h2222lo
    }
    
    int main()
    {
        test01();
        system("Pause");
        return 0;
    }

    结果:

  • 相关阅读:
    harbor无法登陆解决
    k8s中使用harbor
    harbor扩容
    harbor设置开机自启
    设置开机自启
    关Java的内存模型(JMM)
    多线程相关概念
    多线程(JDK1.5的新特性互斥锁)
    synchronized关键字
    【异常】redis.clients.jedis.exceptions.JedisDataException: ERR unknown command 'PSETEX'
  • 原文地址:https://www.cnblogs.com/yifengs/p/15188696.html
Copyright © 2020-2023  润新知