1

I have a string like @"(256) 435-8115" or @"256-435-81-15". I need only the digits (this is a phone number). Is this possible? I haven't found an NSString method to do that.

jscs
  • 63,694
  • 13
  • 151
  • 195
Stas
  • 9,925
  • 9
  • 42
  • 77
  • take a look at NSRegularExpression: https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html – CarlJ May 11 '12 at 09:14
  • Duplicate of http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring – Parag Bafna May 11 '12 at 09:34

3 Answers3

6

I think there is much simpler way:

-(NSString*)getNumbersFromString:(NSString*)String{
    NSArray* Array = [String componentsSeparatedByCharactersInSet:
                      [[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSString* returnString = [Array componentsJoinedByString:@""];

    return (returnString);

}
Mehdzor
  • 789
  • 4
  • 9
  • 23
1

Input:

NSString *stringWithPhoneNumber=@"(256) 435-8115";



NSArray *plainNumbersArray= 

[stringWithPhoneNumber componentsSeparatedByCharactersInSet:

[[NSCharacterSet decimalDigitCharacterSet]invertedSet]];



NSString *plainNumbers = [plainNumbersArray componentsJoinedByString:@""];


NSLog(@"plain number is : %@",plainNumbers);

OutPut: plain number is : 2564358115

0

You can use stringByReplacingOccurrencesOfString: withString: to remove characters you don't want such as @"(" with @""

Ravi Kumar Karunanithi
  • 2,151
  • 2
  • 19
  • 41