NSString方法stringByTrimmingCharactersInSet:不修剪逗号

时间:2013-03-27 05:17:48

标签: ios nsstring nscharacterset

我有以下代码用于从表示数字的某些字符串中删除多余的字符:

NSCharacterSet *charactersToKeep = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *charactersToBeRemoved = [charactersToKeep invertedSet];

NSString *myString = [dictionary objectForKey:@"MyKey"];
myString = [myString stringByTrimmingCharactersInSet:charactersToBeRemoved];
myString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];

在方法stringByTrimmingCharactersInSet:之后,删除除逗号之外的所有额外字符。调用stringByReplacingOccurencesOfString:后,删除逗号。第一次通话后为什么不删除?

以下是每行代码后myString的示例:

myString = " $9,959 "
myString = "9,959"
myString = "9959"

我也试过

NSCharacterSet *charactersToBeRemoved = [NSCharacterSet decimalDigitCharacterSet];

得到了相同的结果。

1 个答案:

答案 0 :(得分:7)

stringByTrimmingCharactersInSet:仅修剪字符串末尾的字符,而不是内部字符。