iPhone地址簿 - 只能将电话号码作为字符串

时间:2014-07-29 10:54:41

标签: ios abaddressbook number-formatting phone-number

我从地址簿中获取了一个电话号码,并将其放入NSString *:

ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
NSString *phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);

我想只将数字作为一个直字符串(意思是没有像(,),+, - 这样的字符)。

当我执行上面的代码并检查NSLog(@"phone is %@", phone);时,我得到:phone is 1 (800) 800-8000

实际上在Xcode控制台中,我看到之前的'('以及'之后)'有一个中心点标志没有正确复制到这个帖子。

我的目标是将1 (800) 800-8000转为此18008008000。我该怎么办?

2 个答案:

答案 0 :(得分:6)

使用以下代码:

NSString *filtered = [[phone componentsSeparatedByCharactersInSet:
    [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                                         componentsJoinedByString:@""];

答案 1 :(得分:3)

你可以在很多方面做到这一点。

一个简单的方法:

NSString *phone = @"1 (800) 800-8000 home";
NSString *strippedNumber = [phone stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [phone length])];

注意: [^0-9]表示0123之外的所有字符,{ {1}},45678