【问题标题】:Convert an iPhone phone number format for a "dial-able" string将 iPhone 电话号码格式转换为“可拨号”字符串
【发布时间】:2012-02-06 23:08:54
【问题描述】:

我正在构建一个 iphone 应用程序,它从地址簿中读取一个电话号码并拨打它(当然还有其他一些事情......:))。当我从 AB 加载电话号码时,它们采用以下格式:“1 (111) 111-1111”,在使用时不能“拨号”:

fullNumber = [NSString stringWithFormat:@"%@%@", @"tel:", phoneNum];

为什么会这样?解决这个问题的最佳方法是什么?如何将电话号码转换为一串数字(没有空格或“-”)?

谢谢。

【问题讨论】:

    标签: iphone objective-c ios xcode nsstring


    【解决方案1】:

    这将删除所有非数字字符:

    phoneNumDecimalsOnly = [[phoneNum componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
    

    【讨论】:

    • 国际号码的“+”号怎么样?
    【解决方案2】:

    要回答有关从字符串中删除特定字符的问题...查看NSString Class Reference,特别是方法stringByReplacingOccurrencesOfString:withString:

    你可以的

    fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
    fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
    fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
    fullNumer = [fullNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    

    显然不是最有效的......但它应该让您了解该方法以及如何去除特定字符。

    在下面的 SO 帖子中可以看到涵盖除数字以外的任何字符的另一个选项,这可能是解决您问题的更好方法。

    Remove all but numbers from NSString

    【讨论】:

      【解决方案3】:

      下面的代码将只允许在输入的字符串中使用数字和+

      phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:
                  [[NSCharacterSet characterSetWithCharactersInString:@"+0123456789"]
                   invertedSet]]
                 componentsJoinedByString:@""];
      

      【讨论】:

        猜你喜欢
        • 2014-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 2011-06-12
        • 2016-04-05
        • 2013-03-19
        相关资源
        最近更新 更多