I want to remove the substring of my string , it looks something like this :
At(Robot,Room3)
or
SwitchOn(Room2)
or
SwitchOff(Room1)
How can I remove all the characters from the left bracket (
to the right bracket )
, when I don't know their indexes ?
If you know the string matches the pattern then you can do:
std::string str = "At(Robot,Room3)";
str.erase( str.begin() + str.find_first_of("("),
str.begin() + str.find_last_of(")"));
or if you want to be safer
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...
You can also use the standard library <regex>
.
std::string str = "At(Robot,Room3)";
str = std::regex_replace(str, std::regex("([^(]*)\\([^)]*\\)(.*)"), "$1$2");
If your compiler and standard library is new enough, then you could use std::regex_replace
.
Otherwise, you search for the first '('
, do a reverse search for the last ')'
, and use std::string::erase
to remove everything in between. Or if there can be nothing after the closing parenthesis then find the first and use std::string::substr
to extract the string you want to keep.
If the trouble you have is actually finding the parentheses the use std::string::find
and/or std::string::rfind
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With