IOS : NSString retrieving a substring from a string

后端 未结 2 1600
广开言路
广开言路 2021-02-05 08:39

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 exampl

相关标签:
2条回答
  • 2021-02-05 08:56

    Try this

    NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];

    NSString* day = [foo objectAtIndex: 0];

    0 讨论(0)
  • 2021-02-05 08:59

    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).

    0 讨论(0)
提交回复
热议问题