【问题标题】:How to find a string in string and replace it?如何在字符串中找到一个字符串并替换它?
【发布时间】:2010-11-17 22:13:31
【问题描述】:

我有一个std::string A,我需要在其中找到字符串B,其内容类似于bla-bla-bla,并将其替换为其他字符串C,例如abcdefg,如果没有找到B,只需输入@987654327 @ 在A 的开头。

这样的事情怎么办?

【问题讨论】:

  • 当你有一些 url 并且你想让它使用类似 'rtmp://' 而不是 'http://' 并且当然你更新知道如果 'http: //'.)
  • 你看过 string::replace 和 string::find 吗?

标签: c++ string boost


【解决方案1】:
void replace_or_merge(std::string &a, const std::string &b, const std::string &c)
{
  const std::string::size_type pos_b_in_a = a.find(b);
  if(pos_b_in_a == std::string::npos) {
    a.insert(0, c);
  }
  else {
    a.replace(pos_b_in_a, b.length(), c);
  }
}

【讨论】:

  • +1 / 听起来很合乎逻辑,但最好将 b 和 c 传递为 const std::string&
【解决方案2】:
A.replace(str.find(B), B.length(), C);

您可能想要添加错误检查 ;-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2012-09-11
    • 1970-01-01
    • 2020-12-01
    • 2017-06-16
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多