范围超出界限的子串? [英] 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:
<强> *终止应用程序由于未捕获的异常 '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 0x17d17a8 0x18e71 0x200d 0x1f35)
的libc ++ ABI .dylib:终止调用抛出异常
* 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.
谢谢
推荐答案
你的NSMakeRange(开始,结束)应该是NSMakeRange(开始,结束 - 开始);
Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);
这篇关于范围超出界限的子串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!