NSString中的单独数字显示电话号码

时间:2011-08-23 19:55:38

标签: objective-c ios cocoa-touch nsstring number-formatting

我有NSString这样的东西:

  

4434332124

我怎样才能把它变成这样的东西?

  

443-433-2124

4 个答案:

答案 0 :(得分:12)

这只能在两行中完成,只需使用NSString的stringWithFormat方法,并将电话号码分成单个子串,并将整个事物粘贴在格式字符串中。像这样:

NSString *sPhone = @"4434332124";

NSString *formatted = [NSString stringWithFormat: @"%@-%@-%@", [sPhone substringWithRange:NSMakeRange(A,B)],[sPhone substringWithRange:NSMakeRange(B,C)],
                           [sPhone substringWithRange:NSMakeRange(C,D)]];

编辑:工作代码

NSString *formatted = [NSString stringWithFormat: @"%@-%@-%@", [sPhone substringWithRange:NSMakeRange(0,3)],[sPhone substringWithRange:NSMakeRange(3,3)],
                           [sPhone substringWithRange:NSMakeRange(6,4)]];

答案 1 :(得分:6)

如果你想简单快速地替换你确定的10位数字,那么试试这个正则表达式的例子( iOS> = 3.2 )。

NSString *tenDigitNumber = @"5554449999";
tenDigitNumber = [tenDigitNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})(\\d{4})"
                                                           withString:@"$1-$2-$3"
                                                              options:NSRegularExpressionSearch
                                                                range:NSMakeRange(0, [tenDigitNumber length])];
NSLog(@"%@", tenDigitNumber);

答案 2 :(得分:0)

不像尝试使用NSFormatter做一些漂亮的东西(尽管除非你将它子类化,但我没有看到明显的方法让它做类似电话号码的事情),但你可以这样做:

NSString* newString = [NSString stringWithFormat:@"%c%c%c-%c%c%c-%c%c%c%c" [phoneNumber characterAtIndex:0],
        [phoneNumber characterAtIndex:1],
        [phoneNumber characterAtIndex:2],
        [phoneNumber characterAtIndex:3],
        [phoneNumber characterAtIndex:4],
        [phoneNumber characterAtIndex:5],
        [phoneNumber characterAtIndex:6],
        [phoneNumber characterAtIndex:7],
        [phoneNumber characterAtIndex:8],
        [phoneNumber characterAtIndex:9]];

答案 3 :(得分:0)

#import <Foundation/Foundation.h>
static NSString * const theInString = @"4434332124";

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    const char      * theUniChar = theInString.UTF8String;
    NSMurableString * theResult = nil;


    for( int i = 0, c = (int)strlen(theUniChar); i < c; i+=2 )
    {
        char     thePart[4];
        sscanf( theUniChar + i, "%3s", &thePart );
        if( theResult == nil )
            theResult = [NSMutableString string];
        else
            [theResult appendFormate:@"-%3s",thePart];
    }

    printf( "%@\n", theResult );

    [pool drain];
    return 0;
}