0

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

致命异常 NSRangeException -[__NSCFString replaceOccurrencesOfString:withString:options:range:]: Range {0, 7} out of bounds; 字符串长度 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];
    }
}
4

1 回答 1

2

完成第一次替换操作后,字符串比构建范围时的字符串短(您正在替换没有任何内容的字符)。原始初始化

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];
于 2013-10-07T17:32:53.300 回答