I want to find the most effective way to do something like this:
A big string containing all kinds of data, for example:
plushieid:5637372&plushieposition:12757&plushieowner:null&totalplushies:5637373
I want to make a function that would have the input to be, let's say "plushieposition"
, and I would have it find and return the string with plushieposition:12757
.
The only way I can think of is find the position of plushieposition
and then scan for &
and delete the rest. But, is there a cleaner way? If not, what would be the best way to do this in code?
I'm having a little bit of trouble understanding string scan practices.
CodePudding user response:
Use std::string::find()
to find the starting and stopping positions, and then use std::string::substr()
to extract what is between them, eg:
string extract(const string &s, const string &name)
{
string to_find = name ":";
string::size_type start = s.find(to_find);
if (start == string::npos) return "";
string::size_type stop = s.find('&', start to_find.size());
return s.substr(start, stop - start);
}
string s = "plushieid:5637372&plushieposition:12757&plushieowner:null&totalplushies:5637373";
string found = extract(s, "plushieposition");