[英]Replace substring within a string c++
我想替换字符串中的子字符串 ,例如:字符串是aa0_a a1_b b3_c * a0_a,所以我想用b1_a替换子字符串a0_a,但是我不希望aa0_a被替换。 基本上,在子字符串“ a0_a”(要替换)之前和之后都不应出现字母。
这就是正则表达式所擅长的。 自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
}
}
}
请注意,在查看子字符串时,您将需要检查索引是否超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.