gpt4 book ai didi

c++ - 使用 erase 从 std::string 从 "("到 ")"删除字符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:02:31 25 4
gpt4 key购买 nike

我想删除字符串的子字符串,它看起来像这样:

At(Robot,Room3)

SwitchOn(Room2)

SwitchOff(Room1)

当我不知道它们的索引时,如何删除左括号 ( 到右括号 ) 中的所有字符?

最佳答案

如果你知道字符串与模式匹配,那么你可以这样做:

std::string str = "At(Robot,Room3)";
str.erase( str.begin() + str.find_first_of("("),
str.begin() + str.find_last_of(")"));

或者如果你想更安全

auto begin = str.find_first_of("(");
auto end = str.find_last_of(")");
if (std::string::npos!=begin && std::string::npos!=end && begin <= end)
str.erase(begin, end-begin);
else
report error...

您还可以使用标准库 <regex> .

std::string str = "At(Robot,Room3)";
str = std::regex_replace(str, std::regex("([^(]*)\\([^)]*\\)(.*)"), "$1$2");

关于c++ - 使用 erase 从 std::string 从 "("到 ")"删除字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13879718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com