【发布时间】:2010-09-15 21:15:26
【问题描述】:
在一次采访中被问到这个问题,我的解决方案有点糟糕,所以我想知道是否有人可以做得更好。
给定一个这种形式的 URL 字符串:
http://www.foo.com?key1=value1&key2=value2&key3=value3 并给出一个密钥
我想创建一个函数,它接受一个键值并返回没有键和值的原始字符串。
例子:
输入:
http://www.foo.com?key1=value1&key2=value2&key3=value3
remove: key2 and its value
输出:
http://www.foo.com?key1=value1&key3=value3
我的解决方案是这样的:
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;
}
但它很丑陋,并且会导致几个测试用例失败。我知道有人有更聪明的方法来做到这一点。有人吗?
【问题讨论】: