什么是在iOS上使用非常长的NSString进行大量NSRange调用的最快方法?

时间:2013-11-29 02:52:16

标签: ios objective-c cocoa-touch nsstring nsrange

我有一段很长的NSString。它包含我需要拉出的大约100个字符串,所有字符串都随机分散。它们通常介于imgurl=&之间。

我可以使用NSRange并循环删除每个字符串,但我想知道是否有更快的方法可以在简单的API调用中选择所有内容?也许我在这里缺少什么?

寻找最快捷的方法。谢谢!

2 个答案:

答案 0 :(得分:2)

使用NSString方法componentsSeparatedByStringcomponentsSeparatedByCharactersInSet

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

答案 1 :(得分:2)

如果您喜欢冒险,那么您可以使用正则表达式。既然你说你正在寻找的字符串在imgurl&之间,我就假设它是一个网址并让示例代码做同样的事情。

    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]]);
    }

如果我是你,我仍然会使用@bobnoble方法,因为与正则表达式相比,它更简单,更简单。您将不得不使用此方法进行更多错误检查。