有很多人遇到需要解析一串url请求地址,如:http://www.baidu.com/hehe?name=1&version=2&test=3
下面这个函数就是具体实现解析的函数。
//解析url字符串对
- (NSDictionary *)parametersWithSeparator:(NSString *)separator delimiter:(NSString *)delimiter url:(NSString *)str{
NSArray *parameterPairs =[str componentsSeparatedByString:delimiter];
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[parameterPairs count]];
for (NSString *currentPair in parameterPairs) {
NSRange range = [currentPair rangeOfString:separator];
if(range.location == NSNotFound)
continue;
NSString *key = [currentPair substringToIndex:range.location];
NSString *value =[currentPair substringFromIndex:range.location + 1];
[parameters setObject:value forKey:key];
}
return parameters;
}
例如我需要取得http://www.baidu.com/hehe?name=1&version=2&test=3中的version的值
先解析name=1&version=2&test=3:
NSDictionary *pair = [self parametersWithSeparator:@"=" delimiter:@"&" url:@"name=1&version=2&test=3"];
然后取得version的值
NSString *value = [pair objectForKey:@"version"];