gpt4 book ai didi

ios - 致命异常 NSRangeException -[__NSCFString replaceOccurrencesOfString :withString:options:range:]: Range {N, N} 越界;字符串长度 N

转载 作者:行者123 更新时间:2023-11-28 22:24:54 34 4
gpt4 key购买 nike

我从下面的代码中收到以下错误,我不确定为什么。

致命异常 NSRangeException-[__NSCFString replaceOccurrencesOfString:withString:options:range:]: 范围{0, 7} 越界;字符串长度 6

我想知道是否有人可以解释一下?

是否只是我需要新的 NSRange 变量来适应不同的字符串长度?

+(double)removeFormatPrice:(NSString *)strPrice {

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber* number = [currencyFormatter numberFromString:strPrice];

//cater for commas and create double to check against the number put
//through the currency formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSMutableString *mstring = [NSMutableString stringWithString:strPrice];
NSRange wholeShebang = NSMakeRange(0, [mstring length]);

[mstring replaceOccurrencesOfString: [formatter groupingSeparator]
withString: @""
options: 0
range: wholeShebang];

//if decimal symbol is not a decimal point replace it with a decimal point
NSString *symbol = [[NSLocale currentLocale]
objectForKey:NSLocaleDecimalSeparator];
if (![symbol isEqualToString:@"."]) {
[mstring replaceOccurrencesOfString: symbol
withString: @"."
options: 0
range: wholeShebang]; // ERROR HERE
}

double newPrice = [mstring doubleValue];
if (number == nil) {
return newPrice;
} else {
return [number doubleValue];
}
}

最佳答案

在完成第一个替换操作后,字符串比构建范围时更短(您将字符替换为空)。原始初始化

NSRange wholeShebang = NSMakeRange(0, [mstring length]);

现在给出一个范围,其长度太大。示例:

NSMutableString* str = [NSMutableString stringWithString: @"1.234,5"];
NSRange allOfStr = NSMakeRange(0, [str length]);

[str replaceOccurrencesOfString: @"."
withString: @""
options: 0
range: allOfStr];

请注意,str 现在看起来像 1234,5,即它比当时短了一个字符,范围已初始化。

因此,如果您在现在太短的字符串上再次使用该范围,则会出现索引越界错误。在将范围传递给第二个替换操作之前,您应该重新初始化范围。:

allOfStr = NSMakeRange(0, [str length]);

[str replaceOccurrencesOfString: @","
withString: @"."
options: 0
range: allOfStr];

关于ios - 致命异常 NSRangeException -[__NSCFString replaceOccurrencesOfString :withString:options:range:]: Range {N, N} 越界;字符串长度 N,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19231033/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com