2

在IOS中,如何删除从通讯录中获取的+-#*()。例如:

 NSString *txt = @"+1(510)1234567"
 txt = [NSString stringWithFormat:@"tel://%@", txt];
 [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:txt]];

这是一个无效的号码。 [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlToCall]];对这个类型号没用。

我能不能有一些更好的选择,除了使用 [txt stringByReplacingOccurrencesOfString:@"-" withString:@""]...。我只是想打个电话。

谢谢你的帮助。


实际上:我们可以通过openURL进行调用:调用的格式不是“tel://”,而是“tel:”。所以,我应该做的是:

NSString *cleanedString = [[phoneNumber componentsSeparatedByCharactersInSet:  
  [[NSCharacterSet characterSetWithCharactersInString:@"0123456789-+()"] 
invertedSet]]     componentsJoinedByString:@""];
NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", cleanedString]];

没关系。

———————————————————————————————— @"tel://" 不是拨打电话的正确网址!我们必须使用@"tel:"

如果不是某个数字,则为 +1 (510) 3436 which
BOOL bCanCall = [[UIApplication sharedApplication]canOpenURL:urlToCall]; 将返回 False。你不能打电话。

4

3 回答 3

3

试试这个,它可能会工作

-(NSString *) formatIdentificationNumber:(NSString *)string
{
    NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"\n_!@#$%^&*()[]{}'\".,<>:;|\\/?+=\t~` "];

    NSString  * result  = @"";
    NSScanner * scanner = [NSScanner scannerWithString:string];
    NSString  * scannerResult;

    [scanner setCharactersToBeSkipped:nil];

    while (![scanner isAtEnd])
    {
        if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
        {
            result = [result stringByAppendingString:scannerResult];
        }
        else
        {
            if(![scanner isAtEnd])
            {
                [scanner setScanLocation:[scanner scanLocation]+1];
            }
        }
    }

    return result;
}

或查看链接

于 2013-04-11T12:22:27.013 回答
3

你可以像这样删除..

NSString *s = @"+1(510)1234567";
NSCharacterSet *unwantedStr = [NSCharacterSet characterSetWithCharactersInString:@"+()"];
s = [[s componentsSeparatedByCharactersInSet: unwantedStr] componentsJoinedByString: @""];
NSLog(@"%@", s); 
于 2013-04-11T12:23:11.883 回答
1

Alternativ,这里有一些提示,但您可以优化代码。

- (void)testExample
{
    NSMutableCharacterSet *mvalidCharSet = [[NSMutableCharacterSet alloc] init];
    [mvalidCharSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet] ];
    [mvalidCharSet addCharactersInString: @"+"]; 
    NSCharacterSet *validCharSet = [mvalidCharSet copy]; // not mutable -> more efficient
    NSCharacterSet *invalidCharSet = [validCharSet invertedSet];
    NSString *txt = @"+1(510)1234567";
    NSArray * components = [txt componentsSeparatedByCharactersInSet:invalidCharSet];
    NSString * rejoin = [components componentsJoinedByString:@""];
    NSLog(@"%@", rejoin);
}
于 2013-04-11T12:31:42.703 回答