简体   繁体   English

c++ - 如何在c ++中删除字符串中的某些字符?

[英]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.

相关问题 如何在C ++中将某些字符复制到字符串中 - how can I copy some characters into string in c++ 只能向字符串添加一定数量的字符 - C++ - Can only add a certain amount of characters to string - C++ 如何从 C++ 中的字符串中删除某些字符? - How to remove certain characters from a string in C++? 如何检查字符串是否包含一定数量的字符并包含(或不包含)某些字符? C ++ - How to check if a string is certain amount of characters and contains (or doesn't contain) certain characters? C++ 如何通过套接字将带有Unicode字符的Java字符串发送到C ++,而没有奇怪的字符? - How can I send a Java string with Unicode characters to C++ via socket, without strange characters? 在 C++ 中删除字符串中所有非字母字符 - Delete all characters in a string that are not alphabetic in C++ 我需要一个函数来从 C++ 中的 char 数组中删除某些字符而不使用任何索引 - I need a function to delete certain characters from a char array in c++ without using any index 如何在C ++中删除变量 - How can I delete variables in C++ 在 C++ 中,如何从字符串中获取接下来的几个字符? - In c++, how can I grab the next few characters from a string? 如何将字符串转换为多个 int 值? C++ - How can I convert a string of characters to multiple int values? C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM