iPhone:Convert NSString (02) 9251 5600 into 0292515600
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:
- constructs a character set composed of all digital characters
- inverts it, so as to get the set composed of everything apart from digital characters
- 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))
- 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.
精彩评论