0

I have a string of phone number with format (123)-(456)-7890 but how can i convert to the following form 1234567890?

Sivaram Yadav
  • 3,141
  • 3
  • 13
  • 15

6 Answers6

2

Try this

NSString *numberString = [[mixedString componentsSeparatedByCharactersInSet:
                [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
                componentsJoinedByString:@""];

It will give digits from a string.

Maulik
  • 19,348
  • 14
  • 82
  • 137
1

stringByReplacingOccurrencesOfString supports also regular expression

NSString *phoneNumber = @"(123)-(456)-7890";
NSString *filteredPhoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"[ ()-]" 
                                 withString:@""
                                    options:NSRegularExpressionSearch 
                                      range:NSMakeRange(0, phoneNumber.length)];
NSLog(@"%@", filteredPhoneNumber);

Put all characters to be ignored between the brackets in the first parameter.

An alternative regex is @"[^\\d+]" which means ignore all non-digit characters

vadian
  • 274,689
  • 30
  • 353
  • 361
0
NSString *str = @"(123)-(456)-7890";
str = [str stringByReplacingOccurrencesOfString: @"(" withString:@""];
str = [str stringByReplacingOccurrencesOfString: @")" withString:@""];
str = [str stringByReplacingOccurrencesOfString: @"-" withString:@""];
NSLog(@"Output = %@",str);

Output = 1234567890

Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
0

You also replacing more character in Single Line of coding using stringByReplacingOccurrencesOfString

NSString *YourString = @"(123)-(456)-7890";
YourString = [[[YourString stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""] stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSLog(@"YourString == > %@",YourString);

YourString == > 1234567890

Bala
  • 1,224
  • 1
  • 13
  • 25
0

Use this code,

NSString *valString = @"(123)456-7890";

NSString* phoneStr=[[[valString stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""] stringByReplacingOccurrencesOfString:@"-" withString:@""];

NSLog(@"phone String %@",phoneStr); // finally you get phone String 1234567890

its working for me, hope its helpful

Iyyappan Ravi
  • 3,205
  • 2
  • 16
  • 30
0

If you want your code to work outside the USA, use Google's telephony library. Formatting and extracting phone numbers is difficult. I wouldn't even try doing it myself by hand.

gnasher729
  • 51,477
  • 5
  • 75
  • 98