Objective-C:删除重复的十进制分隔符

时间:2012-07-22 14:27:05

标签: objective-c ios nsstring comma

我一直在尝试在字符串中使用NSScanner甚至for循环来删除重复的NSDecimalSeparator。怎么做?

注意:NSDecimalSeparator不是“只是一个逗号”。它根据iOS当前的本地化而变化。因此,任何应用搜索重复“逗号”的实现都不起作用。

1 个答案:

答案 0 :(得分:0)

NSDecimalSeparatordeprecated。我建议使用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);