我正在构建一个iphone应用程序,它可以从通讯录中读取电话号码并拨号(当然还有其他一些东西…:))。当我从AB加载电话号码时,它们的格式如下:"1(111)111-1111",使用此时无法"拨号":
fullNumber = [NSString stringWithFormat:@"%@%@", @"tel:", phoneNum];
为什么会发生这种情况?解决这一问题的最佳方法是什么?如何将电话号码转换为一串数字(不带空格或"-")?
谢谢。
这将去掉所有非数字字符:
phoneNumDecimalsOnly = [[phoneNum componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
要回答有关从字符串中删除特定字符的问题。。。看看NSString类引用,特别是方法stringByReplacingOccurrencesOfString:withString:
你可以做
fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
显然不是最有效的。。。但它应该让你了解方法以及如何去掉特定的字符。
在下面的SO帖子中可以看到另一个涵盖数字以外的任何字符的选项,这可能是解决问题的更好方法。
从NSString 中删除除数字以外的所有内容
下面的代码只允许输入字符串中的数字和+
。
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:
[[NSCharacterSet characterSetWithCharactersInString:@"+0123456789"]
invertedSet]]
componentsJoinedByString:@""];