tags:

views:

213

answers:

2

I have std::string with the follwing format

std::string s = "some string with @lable"

I have to find all instances of '@' and then find the identifier right after the '@' , this ID has a value (in this case 'lable' stored for it in a look up table. I will then replace the @ and the id with the found value.

for example suppose the ID label has the value '1000' after the process the string will look like :

"some string with 1000"

my first version used boost::regex, but I had to dump it after I was told that new libs are not allowed in the next few builds.

so is there some elegant way to do it with vanilla std::string and std algorithms ?

+1  A: 

Yes. use std::find to search for @, and then std::find to search for space, and copy everything in between aside.

Pavel Radzivilovsky
+10  A: 

You can use std::find to search for the @, and get a pair of iterators forming a range which begins at the @ and ends at the next white space character (or end of the string). Then just pass the iterators to std::string::replace() to do the actual sub-string replacement.

For example:

std::string s = "some string with @lable";
std::string::iterator beg = std::find(s.begin(), s.end(), '@');
std::string::iterator end = std::find(beg, s.end(), ' ');
s.replace(beg, end, "whatever");

If you also want to count things like tabs or carriage returns as spaces, you can use std::find_if along with std::isspace.

Charles Salvia
+1 . Mine is probably overkill.
Aiden Bell
Don't forget to check that you actually found something to replace. you didn't mention the constraints on your inputs, if there could be more than one occurrence of an ID in a string, if one must always be present etc...
Jeff Paquette