Title: NSString method stringByTrimmingCharactersInSet: not trimming comma
Tags: ios;nsstring;nscharacterset
Question: 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.

Here is the accepted answer: stringByTrimmingCharactersInSet: only trims characters from the ends of the string, not on the inside.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:03/27/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ios><nsstring><nscharacterset>', 'Title': 'NSString method stringByTrimmingCharactersInSet: not trimming comma', 'ViewCount': 2618, 'id': 15652370, 'user_AboutMe': '', 'user_AccountId': 216858.0, 'user_DisplayName': 'Darren', 'user_Reputation': 10002.0, 'user_Views': 261.0, 'user_id': 472344.0}}