简体   繁体   中英

Whats the quickest way to do lots of NSRange calls in a very long NSString on iOS?

I have a VERY long NSString . It contains about 100 strings I need to pull out of it, all randomly scattered throughout. They are all commonly are between imgurl= and & .

I could use NSRange and just loop through pulling out each string, but I'm wondering if there is a quicker was to pick out everything in a simple API call? Maybe something I am missing here?

Looking for the quickest way to do this. Thanks!

Using NSString methods componentsSeparatedByString and componentsSeparatedByCharactersInSet :

NSString *longString = some really long string;
NSArray *longStringComponents = [longString componentsSeparatedByString:@"imgurl="];
for (NSString *string in longStringComponents){
    NSString *imgURLString = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&"]] firstObject];
    // do something with imgURLString...
}

If you feel adventurous then you can use regular expression. Since you said that the string you are looking is between imgurl and & , I assumed its a url and made the sample code to do the same.

    NSString *str = @"http://www.example.com/image?imgurl=my_image_url1&imgurl=myimageurl2&somerandom=blah&imgurl=myurl3&someother=lol";

    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?:imageurl=)(.*?)(?:&|\\r)"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    //should do error checking here...


    NSArray *matches = [regex matchesInString:str
                                      options:0
                                        range:NSMakeRange(0, [str length])];
    for (NSTextCheckingResult *match in matches)
    {
        //[match rangeAtIndex:0] <- gives u the whole string matched.
        //[match rangeAtIndex:1] <- gives u the first group you really care about.
        NSLog(@"%@", [str substringWithRange:[match rangeAtIndex:1]]);
    }

If I were you, I will still go with @bobnoble method because its easier and simpler compared to regex. You will have to do more error checking using this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM