如何在 C++ 中使用 std::string 替换一个字符?

Luc*_*lza 4 c++

如何std::string在 C++ 中使用另一个字符替换一个字符?就我而言,我试图替换每个c由字符的字符。

我试过这种方式:

std::string str = "abcccccd";
str = str.replace('c', ' ');
Run Code Online (Sandbox Code Playgroud)

但是,这行不通。

jua*_*nza 7

使用std::replace算法:

#include <algorithm>
#include <string>
#include <iostream>

int main()
{
  std::string str = "abccccd";
  std::replace(str.begin(), str.end(), 'c', ' ');
  std::cout << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)