Was asked this in an interview, my solution kinda sucked so I am wondering if anyone can do better.
Given a URL string in this form:
http://www.foo.com?key1=value1&key2=value2&key3=value3 and given a key
I want to create a function that takes a key value and returns the original string WITHOUT the key and value.
Example:
input:
http://www.foo.com?key1=value1&key2=value2&key3=value3
remove: key2 and its value
output:
http://www.foo.com?key1=value1&key3=value3
My solution was something like this:
void parseURL(string str, string key)
{
int i;
i = str.find_first_of("?");
string s = str.substr(i);
int start = s.find(key);
int end = 0;
if (start !=string::npos)
end = s.find_first_of("&", start);
string news = str.substr(0, i) + s.substr(0, start-1) + s.substr(end);
cout << news;
}
But it's ugly and it will fail a couple of test cases. I know someone has a more clever way to do this. Anyone?