0

Possible Duplicate:
iphone sdk - Remove all characters except for numbers 0-9 from a string

i have string with a phone number as

mynumber = @"(334)687-6619";

I am using

NSString *phoneURLString = [NSString stringWithFormat:@"tel:%@", phoneNumber];
NSURL *phoneURL = [NSURL URLWithString:phoneURLString];
[[UIApplication sharedApplication] openURL:phoneURL];

to make a call. But due to "(" , ")" my method is not able to make a call.

Please suggest me to make a right string something like

"1-800-555-1212" or something like that.

Thanks

Community
  • 1
  • 1
Shishir.bobby
  • 10,994
  • 21
  • 71
  • 100

3 Answers3

5

You can Use

NSString *s = @"(334)687-6619";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"("];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];

s = [s stringByReplacingOccurrencesOfString:@")" withString:@"-"];
NSLog(@"%@", s);

So, It will replace "(" with "" & replace ")" with "-".

Thanks.

Manann Sseth
  • 2,745
  • 2
  • 30
  • 50
  • 2
    If you're doing it in two steps (which is itself superfluous), you don't even have to use character sets and the split-and-join trick, jnstead you can just use `stringByReplacingOccurrencesOfString:withString:`. –  Jan 16 '13 at 04:29
  • 1
    Ok My friend, It's working. Question was about replacing string. So i've put. – Manann Sseth Jan 16 '13 at 04:33
  • s = [s stringByReplacingOccurrencesOfString:@")" withString:@"-"]; is also working. Thanks mate..:) – Manann Sseth Jan 16 '13 at 04:33
  • 1
    i think @iManan is right . it will work – KDeogharkar Jan 16 '13 at 04:38
3

use this code

NSString *str = @"(334)687-6619";
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];
str = [str stringByReplacingCharactersInRange:NSMakeRange(3, 1) withString:@"-"];    
NSLog(@"%@",str);

OUTPUT is: 334-687-6619

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
2

To remove characters from a string:

NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"()"];
NSArray *comps = [string componentsSeparatedByCharactersInSet:set];
NSString *newString = [comps componentsJoinedByString:@""];