I have the following code for removing extra characters from some strings representing numbers:
NSCharacterSet *charactersToKeep = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *charactersToBeRemoved = [charactersToKeep invertedSet];
NSString *myString = [dictionary objectForKey:@"MyKey"];
myString = [myString stringByTrimmingCharactersInSet:charactersToBeRemoved];
myString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];
After the method stringByTrimmingCharactersInSet:
, all the extra characters but the comma are removed. After the call to stringByReplacingOccurencesOfString:
the comma is removed. Why isn't it removed after the first call?
Here is a sample of what myString looks like after each line of code:
myString = " $9,959 "
myString = "9,959"
myString = "9959"
I also tried
NSCharacterSet *charactersToBeRemoved = [NSCharacterSet decimalDigitCharacterSet];
and got the same result.
stringByTrimmingCharactersInSet: only trims characters from the ends of the string, not on the inside.