How to get a part of a NSString
"http://stackoverflow.com/pqr?name=XYZ&age=26开发者_如何学编程"
for example in the above string i need the value of name that is XYZ. how to get that..?
Thanks
There are methods on NSURL, which you would need to init from the string, that might help. For example, - (NSString *) query
which would give you 'name=XYZ&age=26'. You could then use componentsSeparatedByString(@"&")
to gather each argument and iterate over the resulting array until you get to the key/value you need. Maybe something like:
NSURL *url = [NSURL URLFromString:incomingString];
NSString *queryString = [url query];
NSArray *queryArray = [queryString componentsSeparatedByString(@"&")];
for (NSString *query in queryArray)
{
NSArray *arg = [query componentsSeparatedByString(@"=");
if ([arg count] != 2) continue;
if ([arg objectAtIndex:0] caseInsensitiveCompare:@"SOME_KEY"] == NSOrderedSame)
{
// do something, probably with [arg objectAtIndex:1]
}
}
However, you should be aware of encoding with the incoming string. For example, percent escapes.
Try to split up the string with NSString's method
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
Use "?", "=" and "&" as seperators and then you should be good to go.
精彩评论