C++:replace实现字符替换

    技术2022-07-10  117

    ##C++ string中的replace函数详解 1.应用一:string &replace(size_t pos,size_t len,const &str)被替换位置(pos往后len个字符) 2.应用二:string &replace(size_t pos,size_tlen,const string &str,size_t subpos,size_t sublen)被替换位置(pos往后len长度),替换位置(subpos往后sublen长度) 3.应用三:string &replace(size_t pos,size_t len,const char* s) 插入C串 4.应用四:string &replace(size_t pos,size_t len,const char* cch,size_t n)插入C串前n个字符 5.应用五:string &replace(size_t pos,size_t len,size_t n,char c)在指定位置插入指定个c字符 6.应用六~应用九:(往后为迭代器操作) string &replace(const_iterator it1,const_iterator it2,const string&str) string &replace(const_iterator it1,const_iterator it2,const char* cch) string &replace(const_iterator it1,const_iterator it2,const char* cch,size_t n) string &replace(const_iterator it1,const_iterator it2,size_t n,char c)  

    使用应用五,实现对指定字符的替换。'_'替换为' '。

    #include <iostream> #include <string> using namespace std; int main() { string abc("ff_00_0000"); cout << "old string:" << abc.c_str() << endl; for(int i = 0; i < abc.size(); i++) { if(abc.at(i) == '_') { abc.replace(i, 1, 1, ' '); } } cout << "new string:" << abc.c_str() << endl; return 0; }

     程序运行结果:

    old string:ff_00_0000 new string:ff 00 0000

    Processed: 0.017, SQL: 12