如何替换字符串中所有出现的字符?

新手上路,请多包涵

std::string 中的另一个字符替换所有出现的字符的有效方法是什么?

原文由 big-z 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 741
2 个回答

std::string 不包含此类功能,但您可以使用独立的 replace 功能来自 algorithm 标头。

 #include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

原文由 Kirill V. Lyadvinsky 发布,翻译遵循 CC BY-SA 3.0 许可协议

如何仅使用旧的 C 字符串函数将任何字符串替换为任何字符串?

 char original[256]="First Line\nNext Line\n", dest[256]="";
char* replace_this = "\n"; // this is now a single character but could be any string
char* with_this = "\r\n"; // this is 2 characters but could be of any length

/* get the first token */
char* token = strtok(original, replace_this);

/* walk through other tokens */
while (token != NULL) {
    strcat(dest, token);
    strcat(dest, with_this);
    token = strtok(NULL, replace_this);
}

dest 现在应该有我们正在寻找的东西。

原文由 chara 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题