Substring with range out of bounds?

前端 未结 4 1646
一生所求
一生所求 2020-12-20 17:29

Okay, so this is a bit confusing (well to me). I have a string that has a single number I want out of it. I have surrounded this number with \'/\' so that I will be able to

4条回答
  •  情话喂你
    2020-12-20 17:59

    When the compiler runs into this code...

    else{   
        end = i + 1;
    }
    

    ... in the last iteration of the loop, it sets the end variable to one more then the range of MYSTRING. This is why you are getting that error. To fix it, just do this:

    else{   
        end = i;
    }
    

    Hope this helps!

    P.S. Saleh's approach is a simpler way of accomplishing what you want

    ------UPDATE------

    You should do it like this actually:

    NSMutableArray *occurencesOfSlashes = [[NSMutableArray alloc] init];
    char looking = '/';
    for(int i=0; i < MYSTRING.length; i++){
    if ([MYSTRING characterAtIndex:i] == looking) {
        [occurencesOfSlashes addObject:[NSNumber numberWithInt:i]];  
    }
    NSString *finalString = [MYSTRING substringWithRange:NSMakeRange([occurencesOfSlashes objectAtIndex:0],[occurencesOfSlashes objectAtIndex:1])];
    

提交回复
热议问题