【问题标题】:Replace substring within a string c++替换字符串c ++中的子字符串
【发布时间】:2016-04-02 06:27:06
【问题描述】:

我想替换字符串中的子字符串, 例如:字符串为 aa0_aa1_bb3_c*a0_a, 所以我想用 b1_a 替换子字符串 a0_a,但我不希望 aa0_a 被替换。 基本上,子字符串“a0_a”(要被替换)之前和之后都不应出现字母表。

【问题讨论】:

标签: c++ string replace substring boolean-expression


【解决方案1】:

这就是正则表达式所擅长的。从 C++11 开始就存在于标准库中,如果你有旧版本,你也可以使用 Boost。

使用标准库版本,您可以这样做 (ref):

std::string result;
std::regex rx("([^A-Za-Z])a0_a[^A-Za-Z])");
result = std::regex_replace("aa0_aa1_bb3_c*a0_a", rx, "$1b1_a$2");

(注意:未经测试)

【讨论】:

  • 谢谢,它正在工作,唯一的问题是 $1 打印整个 rx 子字符串,而我们只想要该子字符串的第一个字符
  • 用括号分隔字符串这样做了.. ([^A-Za-z])(a0_a).. 正则表达式将其分成两部分.. 所以 $1 只会占用第一部分,即[^A-Za-z]
【解决方案2】:

如果你循环遍历每个字符,这很容易做到。一些伪代码:

string toReplace = "a0_a";
for (int i = 0; i < myString.length; i++) {
  //filter out strings starting with another alphabetical char
  if (!isAlphabet(myString.charAt(i))) {
    //start the substring one char after the char we have verified to be not alphabetical
    if (substring(myString(i + 1, toReplace.length)).equals(toReplace)) {
      //make the replacement here
    }
  }
}

请注意,在查看子字符串时,您需要检查索引是否越界。

【讨论】:

  • 是的,这适用于小字符串,但我会多次执行此操作,迭代字符串的每个字符会很乏味.....
  • 所以,每次我们可以查找子字符串,然后检查位置(索引-1)的字符,是否是一个字母.....有没有更快的方法,就像现在一样我正在使用 boost::replace_all,想要一个类似的功能也可以考虑到这种情况
猜你喜欢
  • 1970-01-01
  • 2012-04-03
  • 2013-07-23
  • 2014-06-09
  • 2016-02-25
  • 1970-01-01
相关资源
最近更新 更多