Stas
Stas

Reputation: 9935

Getting digits from an NSString

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.

Upvotes: 1

Views: 775

Answers (3)

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

Upvotes: 1

Mehdzor
Mehdzor

Reputation: 799

I think there is much simpler way:

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

    return (returnString);

}

Upvotes: 6

Ravi Kumar Karunanithi
Ravi Kumar Karunanithi

Reputation: 2218

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

Upvotes: 0

Related Questions