[英]How can I delete certain characters in a string in c++?
For example, if i'm taking in the string below.例如,如果我接受下面的字符串。
"{{((A+b)-xyz)addf}sss}";
I would like to ignore all characters that aren't a parenthesis or curly bracket, resulting.我想忽略所有不是括号或大括号的字符,结果。
"{{(())}}"
What method would be most efficient to do.什么方法最有效。
You didn't specify how exactly you obtain the string, but considering:您没有指定获取字符串的确切方式,而是考虑:
std::string str = "{{((A+b)-xyz)addf}sss}";
You could use the erase-remove
idiom.您可以使用erase-remove
习语。 We specify a custom deleter, which will be a function (actually a lambda - a functor) that will check for a character not being a curly bracket or a parenthesis.我们指定了一个自定义删除器,它将是一个函数(实际上是一个 lambda - 一个函子),它将检查不是大括号或圆括号的字符。
auto deleter = [](const char c){
return c != '(' && c != ')' && c != '{' && c != '}';
};
Then we use erase-remove
idiom:然后我们使用erase-remove
成语:
str.erase(std::remove_if(str.begin(), str.end(), deleter), str.end());
This will result in the original str
turning into: {{(())}}
.这将导致原始str
变成: {{(())}}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.