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会替换所有出现的目标字符

  • 相关阅读:
    计蒜客38228 Max answer 单调栈 + 线段树
    Codeforces 103D Time to Raid Cowavans 分块
    Poj 2352 Stars
    HDU 6203 ping ping ping LCA + 贪心
    redis——数据库发展
    数据库拆分
    java基础算法
    docker部署redis集群
    docker网络
    DockerFile
  • 原文地址:https://www.cnblogs.com/youxin/p/2550091.html
Copyright © 2011-2022 走看看