Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从“std::string”中删除字符;(至)";用抹掉?_C++_String_Std_Erase - Fatal编程技术网

C++ 从“std::string”中删除字符;(至)";用抹掉?

C++ 从“std::string”中删除字符;(至)";用抹掉?,c++,string,std,erase,C++,String,Std,Erase,我想删除字符串的子字符串,它看起来像这样: At(Robot,Room3) 或 或 当我不知道其索引时,如何删除左括号(到右括号)中的所有字符 如果您的编译器和标准库足够新,那么您可以使用 否则,您将搜索第一个”(“”,反向搜索最后一个)”,并使用删除中间的所有内容。或者,如果右括号后不能有任何内容,则找到第一个,并使用提取要保留的字符串 如果您遇到的问题是实际查找括号和/或。如果您知道字符串与模式匹配,则可以执行以下操作: std::string str = "At(Robot,Room3)

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

At(Robot,Room3)


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

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

否则,您将搜索第一个
”(“
”,反向搜索最后一个
)”
,并使用删除中间的所有内容。或者,如果右括号后不能有任何内容,则找到第一个,并使用提取要保留的字符串


如果您遇到的问题是实际查找括号和/或。

如果您知道字符串与模式匹配,则可以执行以下操作:

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...

您必须搜索第一个“(”然后在“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);

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

会有嵌套的括号吗?@Shahbaz:不会,只有一个
和一个
。你熟悉吗?
1st
建议很好!+1&selected。有效,但如果你有,比如说
hugestring(tiny),它会有点效率低下
,因为您在同一范围内搜索了两次。@KerrekSB切换到
查找
的最后一个,尽管它仍然可能效率低下,例如
极小(极小)hugestring
。是的,同样的问题。有效的方法是在第一个括号之后继续搜索。@ypriverol正则表达式的功能不足以处理匹配的括号,正则表达式方法在这种情况下不起作用。另一种方法可以很好地工作,因为它只是删除第一个开始括号之间的所有内容n和最后一个结束参数。
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...
std::string str = "At(Robot,Room3)";
str = std::regex_replace(str, std::regex("([^(]*)\\([^)]*\\)(.*)"), "$1$2");
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);