IOS : NSString retrieving a substring from a string

iosiphonensstringstring

Hey I am looking for a way to extract a string from another string. It could be any length and be in any part of the string so the usual methods don't work.

For example
http://bla.com/bla?id=%1234%&something=%888%

What I want to extract is from id=% to the next %.

Any idea's?

Best Solution

Use the rangeOfString method:

NSRange range = [string rangeOfString:@"id=%"];
if (range.location != NSNotFound)
{
   //range.location is start of substring
   //range.length is length of substring
}

You can then chop up the string using the substringWithRange:, substringFromIndex: and substringToIndex: methods to get the bits you want. Here's a solution to your specific problem:

NSString *param = nil;
NSRange start = [string rangeOfString:@"id=%"];
if (start.location != NSNotFound)
{
    param = [string substringFromIndex:start.location + start.length];
    NSRange end = [param rangeOfString:@"%"];
    if (end.location != NSNotFound)
    {
        param = [param substringToIndex:end.location];
    }
}

//param now contains your value (or nil if not found)

Alternatively, here's a general solution for extracting query parameters from a URL, which may be more useful if you need to do this several times:

- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
    NSString *queryString = [URL query];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    NSArray *parameters = [queryString componentsSeparatedByString:@"&"];
    for (NSString *parameter in parameters)
    {
        NSArray *parts = [parameter componentsSeparatedByString:@"="];
        if ([parts count] > 1)
        {
            NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            result[key] = value;
        }
    }
    return result;
}

This doesn't strip the % characters from the values, but you can do that either with

NSString *value = [[value substringToIndex:[value length] - 1] substringFromIndex:1];

Or with something like

NSString *value = [value stringByReplacingOccurencesOfString:@"%" withString:@""];

UPDATE: As of iOS 8+ theres a built-in class called NSURLComponents that can automatically parse query parameters for you (NSURLComponents is available on iOS 7+, but the query parameter parsing feature isn't).