C++ 标准库 - <string>

C++ std::string::replace() 用另一段文本替换当前串中从 pos 起长度为 count 的区间,长度可以变长或变短。

原型

string& replace(size_t pos, size_t count, const string& str);
string& replace(size_t pos, size_t count, const char* s);

参数

  • pos:被替换区间起点。
  • count:被替换的字符数。
  • str / s:新内容。

返回值

返回 *this。区间越界时抛出 std::out_of_range。

示例

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello C";
    s.replace(6, 1, "C++");
    std::cout << s << std::endl;
    return 0;
}

输出:

Hello C++

注意事项

只替换第一次出现的子串时,通常先 find 得到 pos,再以子串长度为 count 调用 replace。替换全部出现需要循环,并注意新串中再次包含目标时的下标推进。

下一页介绍at:带检查的字符访问。