简体   繁体   中英

Removing all non wanted characters using the NSCharacterSet

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:@"" ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM