子范围越界?

好吧,这有点混乱(对我来说)。 我有一个string,我想要一个单一的数字。 我已经用“/”包围了这个数字,以便以后能够从中得到这个数字。

下面是我如何从中得到数字:

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

它不断崩溃,控制台说:

*由于未捕获的exception'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调用抛出exception

从我的计数范围是在范围内,我不明白为什么我得到这个错误?

任何帮助,将不胜感激。

谢谢

你的NSMakeRange(start,end)应该是NSMakeRange(start,end-start);

我想你对NSMakeRange的语法有困惑。 这是这样的

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

<#NSUInteger loc#>:它是您要从哪里开始<#NSUInteger loc#>:或子string的位置。

<#NSUInteger len#>:这是您的输出或子string的长度。

例:

Mytest12test

现在我想选'12'

所以:

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

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

我不知道你为什么使用这种方法,但是iOS提供了一个string函数,它将string与另一个string相分离,并返回一个组件数组。 看下面的例子:

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

现在你的组件string应该有2个存储在其中。

当编译器运行到这个代码…

 else{ end = i + 1; } 

…在循环的最后一次迭代中,它将结束variables设置为MYSTRING的范围之外的MYSTRING 。 这就是你得到这个错误的原因。 要解决这个问题,只需要这样做:

 else{ end = i; } 

希望这可以帮助!

PS Saleh的方法是完成你想要的一个简单的方法

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