3-3-2 替换字符串中的字符

3.3.2 替换字符串中的字符

replace函数用于替换字符串中的字符。

1.不同的重载版本

  • (成员函数)指定位置的指定数量的字符串,替换为给定字符串

    • 参数

      • para1:start
      • para2:number
      • para3:replace string(C style or C++ string)
    • simple example:

      •   #include <cassert>
          #include <string>
          using namespace std;
          
          int main(int argc, char const *argv[])
          {
              string s("A place of text");
              string tag("$tag$");
              s.insert(8,tag+' ');
              assert(s == "A place $tag$ of text");
              int start = s.find(tag);
              assert(start == 8);
              assert(tag.size() == 5);
              s.replace(start, tag.size(), "hello there");
              assert(s == "A place hello there of text");
              return 0;
          }
          

        * (全局函数)指定范围内的一个字符替换为另一个字符

        * 参数:

        * para1:开始迭代器
        * para2:结束迭代器
        * para3:查找的字符
        * para4:替换成字符

        * simple example:

        * ```C++
        #include <algorithm>
        #include <cassert>
        #include <string>
        using namespace std;

        int main()
        {
        string s("aaaXaaaXXaaXXXaXXXXaaa");
        replace (s.begin(),s.end(),'X','Y');
        assert(s == "aaaYaaaYYaaYYYaYYYYaaa");
        }

2.string::npos成员(静态常量)

​ 数据成员npos表示一个不存在的字符位置。下面是一个simple example:

#include <cassert>
#include <cstddef>
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;

void replaceChars(string &modifyMe,
const string &fineMe, const string &newChars)
{
size_t i = modifyMe.find(fineMe, 0);
if (i != string::npos) //if not find, get the string::npos
modifyMe.replace(i, fineMe.size(), newChars);
else
throw out_of_range("not found");
}

int main(int argc, char const *argv[])
{
string bigNews = "I thought I saw Elvis in an UFO. "
"I have been working too hard. ";
string replacement("wig");
string findMe("UFO");
try
{
replaceChars(bigNews, findMe, replacement);
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}

assert(bigNews == "I thought I saw Elvis in an wig. I have been working too hard. ");
return 0;
}

3.实现替换所有特征字符串函数

​ 使用findreplace实现

//ReplaceAll.h
#ifndef REPLACEALL_H
#define REPLACEALL_H
#include <string>

std::string& replaceAll(std::string& context,
const std::string& from,
const std::string& to);

#endif


//ReplaceAll.cpp
#include <cstddef>
#include "ReplaceAll.h"
using namespace std;

std::string& replaceAll(std::string& context,
const std::string& from,
const std::string& to)
{
size_t lookHere = 0;
size_t foundHere;
while((foundHere = context.find(from, lookHere))!=string::npos) //find from lookHere
{ //to avoid the string
context.replace(foundHere, from.size(), to); //"to" is the substr
lookHere = foundHere + to.size(); //of "from"
}
return context;
}