|
发表于 2024-10-13 18:08:51
|
显示全部楼层
为了实现字符串中的有序迭代替换,你可以按以下步骤来调整代码,确保每一对括号中的数字独立递增:
1. **遍历字符串中的匹配项**:使用正则表达式逐个匹配,每次只替换匹配到的第一个项。
2. **精确替换匹配项**:在每次匹配后,计算当前匹配的具体位置,并仅替换这一项。
3. **更新结果字符串和迭代器**:因为字符串已被修改,需要更新迭代器起点,以避免不必要的重复替换。
以下是更新后的代码示例:
- #include <iostream>
- #include <string>
- #include <regex>
- std::string AddFunProduct::replace_and_increment(std::string input, std::regex pattern) {
- std::string result = input;
- std::sregex_iterator it(input.begin(), input.end(), pattern);
- std::sregex_iterator end;
- while (it != end) {
- std::smatch match = *it;
- std::string matchStr = match.str();
- // 去掉括号
- matchStr.erase(0, 1);
- matchStr.erase(matchStr.length() - 1, 1);
- // 提取并递增数字
- int num = std::stoi(matchStr) + 1;
- // 替换仅匹配到的项
- std::string replacement = "(" + std::to_string(num) + ")";
- result.replace(match.position(), match.length(), replacement);
- // 更新迭代器动点指向经过替换之后新的位置
- it = std::sregex_iterator(result.begin() + match.position() + replacement.length(), result.end(), pattern);
- }
- return result;
- }
- int main() {
- std::string input = "\n(2)333\n(3)444";
- std::regex pattern("\\(\\d+\\)");
- AddFunProduct obj;
- std::string result = obj.replace_and_increment(input, pattern);
- std::cout << result << std::endl;
- return 0;
- }
复制代码
注意几个关键点:
- 使用 `match.position()` 和 `match.length()` 来确定当前匹配的具体位置和长度,以便精确替换。
- 每次替换后,重新计算并设置迭代器位置以继续匹配下一个项。
这样通过准确替换每一个匹配项,就可以实现目标效果。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|