替换字符串中的子字符串 C++

Replace substring within a string c++

我想替换字符串中的子字符串, 例如:字符串是 aa0_aa1_bb3_c*a0_a, 所以我想用 b1_a 替换子字符串 a0_a,但我不希望 aa0_a 被替换。 基本上,子字符串 "a0_a"(将被替换)前后不应出现任何字母表。

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

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
    }
  }
}

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

这就是正则表达式所擅长的。从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, "b1_a");

(注意:未经测试)