0

I have a NSString that contains fax telephone numbers. Sometimes I get different 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

EmptyStack
  • 51,274
  • 23
  • 147
  • 178
Strong Like Bull
  • 11,155
  • 36
  • 98
  • 169
  • possible duplicate of [Making a phone call in an iOS application](http://stackoverflow.com/questions/6323171/making-a-phone-call-in-an-ios-application) – PengOne Jun 13 '11 at 05:34
  • 2
    @PengOne while this question and the one you linked are related it is not a duplicate. – UnkwnTech Jun 13 '11 at 05:55

1 Answers1

1

Using NSCharacterSet and NSMutableCharacterSet you can solve this problem in two ways.

  1. If you already know the characters that you want to remove.

    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+-(),. "];
    NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet];
    NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
    
  2. 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:@""];
    
EmptyStack
  • 51,274
  • 23
  • 147
  • 178