I have a NSString that contains fax telephone numbers. Sometimes I get different 开发者_C百科formats entered for example: (877) xxx-xxxx or 877-xxx-xxxx.
How do I get about cleaning the NSSString so that all I get is XXXxxxxxx.
Thanks
Using NSCharacterSet
and NSMutableCharacterSet
you can solve this problem in two ways.
If you already know the characters that you want to remove.
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+-(),. "]; NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet]; NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
If you don't know the characters, you can use the different character sets available already
NSMutableCharacterSet *charSet = [NSMutableCharacterSet new]; [charSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]]; [charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]]; [charSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]]; NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet]; NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
精彩评论