Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple wildcard match with std::string

Tags:

c++

string

stl

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 ?

like image 615
Eli Avatar asked May 15 '26 13:05

Eli


1 Answers

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 ::isspace.

like image 77
Charles Salvia Avatar answered May 18 '26 01:05

Charles Salvia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!