zoukankan      html  css  js  c++  java
  • c++ string 替换

     可以用string的成员函数replace 或 算法库里的replace函数

    string& replace ( size_t pos1, size_t n1,   const string& str );
    还有很多的函数参数形式。
    replace之前可以用string 成员函数find找到你想替换的字符串

    string::find

    size_t find ( const string& str, size_t pos = 0 ) const;
    size_t find ( const char* s, size_t pos, size_t n ) const;
    size_t find ( const char* s, size_t pos = 0 ) const;
    size_t find ( char c, size_t pos = 0 ) const;

    string  str="hello-world";
        int foundPos=str.find('-',0);
        if(foundPos!=string::npos)
            str.replace(foundPos,1,"   ");
        cout<<str<<endl;

    会替换-为两个空格。上面的代码只能替换第一次出现的字符,对于多个,可以用循环,或直接用stl的replace。

    直接用stl的replace;

    template < class ForwardIterator, class T >
      void replace ( ForwardIterator first, ForwardIterator last,
                     const T& old_value, const T& new_value );


    string str="hello-world-welcome-to-masm";
      
        replace(str.begin(),str.end(),'-',' ');
        cout<<str<<endl;

    注意str.begin()所指类型应和后面的两个参数类型一致,如果写成以下几种形式;

    replace(str.begin(),str.end(),"-"," ");
    replace(str.begin(),str.end(),'-'," ");

    都是不行的。因为str.begin()所指的是字符。所以只能用字符来替换。

      stl的replace会替换所有出现的目标字符

  • 相关阅读:
    pip安装requests时报 Requirement already satisfied: requests in d:pythonpyth... 的问题解决
    渗透测试靶场
    Spring Security核心类关系图
    Spring security 5 Authorize Configuration
    固定技术栈
    redis 指定端口 启动
    Spring 获取当前activeProfile
    通过进程编号 查询 监听端口
    lombok 插件安装
    idea 快捷键设置
  • 原文地址:https://www.cnblogs.com/youxin/p/2550091.html
Copyright © 2011-2022 走看看