解析URL字符串以获取键的值的最佳方法? [英] Best way to parse URL string to get values for keys?

查看:145
本文介绍了解析URL字符串以获取键的值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析这样的网址字符串:

I need to parse a URL string like this one:

&ad_eurl=http://www.youtube.com/video/4bL4FI1Gz6s&hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104



我需要将NSString拆分成签名部分,如 cid = 241 & avg_rating = 4.82280613104 。我一直这样做与 substringWithRange:但是值返回一个随机的顺序,所以弄混了。是否有任何类,允许容易解析,你可以基本上转换为NSDictionary以能够读取一个键的值(例如ValueForKey: cid 应该返回 241 )。或者只是另一种更简单的方法来解析它,而不是使用 NSMakeRange 来获取子字符串?

I need to split the NSString up into the signle parts like cid=241 and &avg_rating=4.82280613104. I've been doing this with substringWithRange: but the values return in a random order, so that messes it up. Is there any class that allows easy parsing where you can basically convert it to NSDictionary to be able to read the value for a key (for example ValueForKey:cid should return 241). Or is there just another easier way to parse it than using NSMakeRange to get a substring?

推荐答案

我会创建一个字典,得到一个键/值对的数组

I would create a dictionary, get an array of the key/value pairs with

NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSArray *urlComponents = [urlString componentsSeparatedByString:@"&"];

然后填入字典:

for (NSString *keyValuePair in urlComponents)
{
    NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
    NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
    NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];

    [queryStringDictionary setObject:value forKey:key];
}

然后您可以使用

[queryStringDictionary objectForKey:@"ad_eurl"];

这是未经测试的,你应该做一些更多的错误测试。

This is untested, and you should probably do some more error tests.

这篇关于解析URL字符串以获取键的值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆