从 std::字符串中删除字符从 "(" 到 ")" 用擦除?



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

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");

如果您的编译器和标准库足够新,那么您可以使用 std::regex_replace .

否则,您可以搜索第一个'(',对最后一个')'进行反向搜索,并使用std::string::erase删除两者之间的所有内容。或者,如果右括号后没有任何内容,则找到第一个并使用std::string::substr提取要保留的字符串。

如果您遇到的麻烦实际上是找到括号,请使用std::string::find和/或std::string::rfind

你必须搜索第一个'(',然后在之后擦除,直到'str.length() - 1'(假设你的第二个括号总是在末尾)

一个简单、安全、高效的解决方案:

std::string str = "At(Robot,Room3)";
size_t const open = str.find('(');
assert(open != std::string::npos && "Could not find opening parenthesis");
size_t const close = std.find(')', open);
assert(open != std::string::npos && "Could not find closing parenthesis");
str.erase(str.begin() + open, str.begin() + close);

切勿多次解析一个字符,小心格式错误的输入。

最新更新