I have a string of phone number with format (123)-(456)-7890 but how can i convert to the following form 1234567890?
Asked
Active
Viewed 734 times
6 Answers
2
Try this
NSString *numberString = [[mixedString componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
It will give digits from a string.

Maulik
- 19,348
- 14
- 82
- 137
-
in case if number formatting is not what is expected, you can always use stringByReplacingOccurrencesOfString as seen in following link http://stackoverflow.com/questions/6638623/uiviewcontentmodescaleaspectfill-not-clipping – Deepak Thakur May 31 '16 at 06:30
-
Thanks alot Maulik – Sivaram Yadav May 31 '16 at 06:46
-
@SivaramYadav : Sure ! you should start accepting the answers. – Maulik May 31 '16 at 06:47
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