【发布时间】: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
我想替换字符串中的子字符串, 例如:字符串为 aa0_aa1_bb3_c*a0_a, 所以我想用 b1_a 替换子字符串 a0_a,但我不希望 aa0_a 被替换。 基本上,子字符串“a0_a”(要被替换)之前和之后都不应出现字母表。
【问题讨论】:
标签: c++ string replace substring boolean-expression
这就是正则表达式所擅长的。从 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");
(注意:未经测试)
【讨论】:
如果你循环遍历每个字符,这很容易做到。一些伪代码:
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
}
}
}
请注意,在查看子字符串时,您需要检查索引是否越界。
【讨论】: