开发者

Help with string manipulation method

开发者 https://www.devze.com 2023-02-25 02:16 出处:网络
I have a method called getTitle which is in a NSString category, and it will remove anything between the strings \"(\" and \")\" and it will also remove those strings. However, when the input string d

I have a method called getTitle which is in a NSString category, and it will remove anything between the strings "(" and ")" and it will also remove those strings. However, when the input string does not contain either of the strings above, the method will crash with the error:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

This is caused by the NSArray 'a' having no objects.

However, I can't seem to fix it. Please could you take a look at the code below and point out the problem?

- (NSString *)getTitle {
    NSArray *a = [self componentsSeparatedByString:@"("];
    if ([a count] > 0) {
        if ([a objectAtIndex:1] != [NSNull null])  {
        NSString *b = [a objectAtIndex:1];
        NSArray *c = [b componentsSeparatedByString:@")"];
        if ([c count] == 0)
            return self;
        if ([a objectAtIndex:0] != nil && [c objectAtIndex:1] !=nil)
            return [[[a objectAtIndex:0] stringByAppendingString:[c objectAtIndex:1]] stringByReplacingOccurrencesOfString:@"  -" withString:@" -"];
        el开发者_如何学Pythonse 
            return self;
        }
            else
                return self;
    }
    else {
        return self;
    }
    return self;
}


It's probably crashing in this line:

if ([a objectAtIndex:1] != [NSNull null])  {

I guess you're trying to check whether componentsSeparatedByString: returned an array with more than one component. The correct way is to check if ([a count] > 1) (or >= 2).


Hmm.. sounds like a string like: @"foo(". In this case, the array will contain only @"foo" and it will crash (because count > 0, but not 2!). You need to check if the array contains at least 2 elements before accessing its second element in if ([a objectAtIndex:1] != [NSNull null]) {


You can do something like this:

NSString *str = @"asdf(asdf)asdf";
    NSRange range;
    range = [str rangeOfString:@"("];
    if( range.location != NSNotFound ){
        int start = range.location;
        range = [str rangeOfString:@")"];
        if( range.location!= NSNotFound ){
            int end = range.location;
            NSLog(@"%@",[NSString stringWithFormat:@"%@%@",[str substringToIndex:start],[str substringFromIndex:end+1]]);
        }
        // return nil;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消