【问题标题】:Can I replace a single character in a string with 2 characters?我可以用 2 个字符替换字符串中的单个字符吗?
【发布时间】:2021-10-06 05:50:48
【问题描述】:
#include <algorithm>
#include <string>

void foo(std::string &s) {
    replace(s.begin(), s.end(), 'S', 'TH');
}

我希望foo(s) 用两个字符TH 替换s 中的每个S。例如

std::string s = "SAT";
foo(s);
std::cout << s << "\n" // THAT

但是,foo 的定义给了我一个错误。

Error (active) E0304 no instance of function template "std::replace" 与参数列表匹配

为什么这不起作用?

【问题讨论】:

  • 你使用过std命名空间吗?试试 std::replace(s.begin(), s.end(), 'S', 'TH)
  • 'TH' 不是有效的语法>对于字符文字
  • @gerum 有效,有条件地支持多字符文字,它们的类型为int:stackoverflow.com/a/34571914/4117728
  • 你说得对,我修好了。

标签: c++ string replace


【解决方案1】:

std::replace 不能这样做,但您可以使用 std::regex_replace 代替。

#include <regex>

std::string s = "SAT";
s = regex_replace(s, std::regex("S"), "TH");
std::cout << s << "\n"; // output: THAT

【讨论】:

  • 你不需要正则表达式,std::string::replace 可以做到
  • @463035818_is_not_a_number,tbh,我试图用 string::replace 找到解决方案,但没有成功。在评论中发布您的答案永远不会晚,我也在从错误中学习!
  • godbolt.org/z/1434nfTT5,尽管应该检查find 的返回值。我发现字符串 memebr 函数也令人困惑,因为它们与算法具有相似的名称,但使用索引而不是迭代器,可能会相当混乱
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多