Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 245
Faz Ya Avatar asked Mar 12 '12 22:03

Faz Ya


1 Answers

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:@"" ];
like image 107
jonkroll Avatar answered Oct 19 '22 11:10

jonkroll