开发者

iPhone:Convert NSString (02) 9251 5600 into 0292515600

开发者 https://www.devze.com 2023-04-06 08:52 出处:网络
I have NSString like (02) 9251 5600 but I want to convert into this format 0292515600 in my apps so please help me to develop this f开发者_运维百科unctionality.

I have NSString like (02) 9251 5600 but I want to convert into this format 0292515600 in my apps so please help me to develop this f开发者_运维百科unctionality.

Thanks in advance.


Thinking as I type, this should do it:

[[string componentsSeparatedByCharactersInSet:
      [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
 componentsJoinedByString:@""]

So that:

  1. constructs a character set composed of all digital characters
  2. inverts it, so as to get the set composed of everything apart from digital characters
  3. asks NSString to return an array of sections of text containing only things that aren't in set (2) (i.e., only things that are in set (1))
  4. asks NSArray to glue all the strings together, inserting the empty string between each

If written as multiple statements for clarity:

NSCharacterSet *decimalDigialCharacterSet = 
                                    [NSCharacterSet decimalDigitalCharacterSet];

NSCharacterSet *everythingButDecimalDigialCharacterSet = 
                                        [decimalDigialCharacterSet invertedSet];

NSArray *componentsNotInSecondSet = [string componentsSeparateByCharactersInSet:
                                          everythingButDecimalDigialCharacterSet];

NSString *componentsGluedTogether = [componentsNotInSecondSet 
                                                   componentsJoinedByString:@""];


NSString *telnumber = @"(02) 9251 5600";

telnumber = [telnumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
telnumber = [telnumber stringByReplacingOccurrencesOfString:@")" withString:@""];
telnumber = [telnumber stringByReplacingOccurrencesOfString:@" " withString:@""];


Use [NSString stringByReplacingOccurancesOfString:] multiple times, and replace @"(",@")" and @" " with @"".

Won't post code, I'm sure you can figure it out from here. Its the quickest and most dirty way to do it, obviously.

0

精彩评论

暂无评论...
验证码 换一张
取 消