Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

objective c - Substring with range out of bounds?

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 get that number out of it later.

Here is how I am getting the number out of it:

if ([MYSTRING hasSuffix:@"mp"]) {
        int start = 0;
        int end = 0;
        char looking = '/';
        for(int i=0; i < MYSTRING.length; i++){
            if (looking == [MYSTRING characterAtIndex:i]) {
                if (start == 0) {
                    start = i;
                }
                else{
                    end = i + 1;
                }
            }
        }
        NSLog(@"%@", MYSTRING); //When i NSLOG here i get '2012-06-21 03:58:00 +0000/1/mp', 1 is the number i want out of the string, but this number could also change to 55 or whatever the user has
        NSLog(@"start: %i, end: %i", start, end); //When i NSLOG here i get 'start: 25, end: 28'
        NSString *number = [MYSTRING substringWithRange:NSMakeRange(start, end)];
        number = [number stringByReplacingOccurrencesOfString:@"/" withString:@""];
        if ([number intValue] > numberInt) {
            numberInt = [number intValue];
        }

It keeps crashing and the console says:

* Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range or index out of bounds' * First throw call stack: (0x1875d72 0x106ce51 0x1875b4b 0x184ea64 0x3a6c 0x1080713 0x1bf59 0x1bef1 0xd532e 0xd588c 0xd49f5 0x49a2f 0x49c42 0x290fe 0x1b3fd 0x17d2f39 0x17d2c10 0x17ebda5 0x17ebb12 0x181cb46 0x181bed4 0x181bdab 0x17d1923 0x17d17a8 0x18e71 0x200d 0x1f35) libc++abi.dylib: terminate called throwing an exception

From my counting the range is within the bounds, I dont get why I am getting this error?

Any help would be appreciated.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...