范围超出界限的子串?

时间:2012-06-21 04:25:42

标签: objective-c ios nsstring

好的,所以这有点令人困惑(对我而言)。我有一个字符串,它有一个我想要的数字。我用'/'包围了这个数字,这样我以后就能得到这个数字了。

以下是我如何获取数字:

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

它一直在崩溃,控制台说:

  

*由于未捕获的异常'NSRangeException'而终止应用程序,原因:' - [__ NSCFString substringWithRange:]:范围或索引超出范围'   * 第一次抛出调用堆栈:   (0x1875d72 0x106ce51 0x1875b4b 0x184ea64 0x3a6c 0x1080713 0x1bf59 0x1bef1 0xd532e 0xd588c 0xd49f5 0x49a2f 0x49c42 0x290fe 0x1b3fd 0x17d2f39 0x17d2c10 0x17ebda5 0x17ebb12 0x181cb46 0x181bed4 0x181bdab 0x17d1923 0x17d17a​​8 0x18e71 0x200d 0x1f35)   libc ++ abi.dylib:terminate调用抛出异常

从我的计算范围是在范围内,我不知道为什么我得到这个错误?

任何帮助都将不胜感激。

由于

4 个答案:

答案 0 :(得分:24)

你的NSMakeRange(开始,结束)应该是NSMakeRange(开始,结束 - 开始);

答案 1 :(得分:6)

我认为你对NSMakeRange的语法感到困惑。它是这样的

NSMakeRange(<#NSUInteger loc#>, <#NSUInteger len#>)

<#NSUInteger loc#>:这是您要开始挑选或子串的位置。

<#NSUInteger len#>:这是输出或子字符串的长度。

示例:

Mytest12test

现在我想选择'12'

这样:

NSString *t=@"Mytest12test";
NSString *x=[t substringWithRange:NSMakeRange(6, 2)] ;

在您的代码而不是长度中,您传递的是结束字符的索引,这是您的错误。

答案 2 :(得分:2)

我不知道你为什么使用这种方法,但iOS提供了一个字符串函数,它将字符串与另一个字符串分开并返回组件的数组。请参阅以下示例:

NSString * str = @"dadsada/2/dsadsa";
NSArray *listItems = [str componentsSeparatedByString:@"/"];
NSString *component = [listItems objectAtIndex:1];

现在你的组件字符串中应该有2个存储区。

答案 3 :(得分:1)

当编译器运行此代码时......

else{   
    end = i + 1;
}

...在循环的最后一次迭代中,它将结束变量设置为一个更多,然后是MYSTRING的范围。这就是您收到该错误的原因。要修复它,只需执行此操作:

else{   
    end = i;
}

希望这有帮助!

P.S。萨利赫的方法是一种更简单的方法来实现你想要的东西

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

你应该这样做:

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