Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove characters from std::string from "(" to ")" with erase ?

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 ?

like image 879
JAN Avatar asked Dec 14 '12 13:12

JAN


2 Answers

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");
like image 77
bames53 Avatar answered Sep 29 '22 19:09

bames53


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.

like image 41
Some programmer dude Avatar answered Sep 29 '22 18:09

Some programmer dude