我一直在尝试在字符串中使用 NSScanner 甚至 for 循环来删除重复的 NSDecimalSeparator。怎么做?
注意: NSDecimalSeparator 不是“只是一个逗号”。它会根据 iOS 当前的本地化而变化。因此,任何应用搜索重复“逗号”的实现都将不起作用。
我一直在尝试在字符串中使用 NSScanner 甚至 for 循环来删除重复的 NSDecimalSeparator。怎么做?
注意: NSDecimalSeparator 不是“只是一个逗号”。它会根据 iOS 当前的本地化而变化。因此,任何应用搜索重复“逗号”的实现都将不起作用。
NSDecimalSeparator
已弃用。我建议使用NSNumberFormatter
:
//getting default formatter
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior: [NSNumberFormatter defaultFormatterBehavior]];
//creating two strings, one with single and one with double separator
NSString *separator = [numberFormatter decimalSeparator];
NSString *doubleSeparator = [NSString stringWithFormat:@"%@%@", separator, separator];
NSLog(@"decimal separator: %@", separator);
//creating example string
NSString *str = [NSString stringWithFormat:@"single: %@ double: %@", separator, doubleSeparator];
NSLog(@"example string: %@", str);
//replacing double separator with single separator
NSString *modified = [str stringByReplacingOccurrencesOfString: doubleSeparator withString:separator];
NSLog(@"modified string: %@", modified);
编辑: 关于您对“23,45,67”字符串的评论,这里是:
NSString *str2 = @"23,45,67";
NSMutableArray *temp = [NSMutableArray arrayWithArray: [str2 componentsSeparatedByString:separator]];
NSString *last = [temp lastObject];
[temp removeLastObject];
NSString *newStr = [NSString stringWithFormat:@"%@%@%@", [temp componentsJoinedByString:@""], separator, last];
NSLog(@"result: %@", newStr);
编辑 2: 仅保留第一个分隔符的代码类似:
NSMutableArray *temp2 = [NSMutableArray arrayWithArray: [str2 componentsSeparatedByString:separator]];
NSString *first = [temp2 objectAtIndex:0];
[temp2 removeObject:first];
NSString *newStr2 = [NSString stringWithFormat:@"%@%@%@", first, separator, [temp2 componentsJoinedByString:@""]];
NSLog(@"result2: %@", newStr2);