I would like to remove all the characters from my NSString that are not (numerical, alphabetical, come, space, or period).
I am using the NSCharacterSet but it does not have a way of adding to it. I tried the mutable version to add in space, comma, and period but haven't been successful.
// str is my string
NSCharacterSet *charactersToRemove =
[[ NSCharacterSet letterCharacterSet ] invertedSet ];
NSString *trimmedReplacement =
[[ str componentsSeparatedByCharactersInSet:charactersToRemove ]
componentsJoinedByString:@"" ];
// this removes spaces, periods, and commas too. How do I add in to the character set to keep them
Create a mutable character set and add the additional characters you want to keep. Also you probably mean to use alphanumericCharacter set instead of letterCharacterSet if you want to keep numbers in your string too.
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:@" ,."];
NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet];
NSString *trimmedReplacement = [[ str componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@"" ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With