2012-05-11 64 views
1

我有一個字符串,如@"(256) 435-8115"@"256-435-81-15"。我只需要數字(這是一個電話號碼)。這可能嗎?我還沒有找到NSString方法來做到這一點。從NSString獲取數字

+0

看看NSRegularExpression:https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html – CarlJ

+0

HTTP的重複:// stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring –

回答

6

我覺得有更簡單的方法:

-(NSString*)getNumbersFromString:(NSString*)String{ 
    NSArray* Array = [String componentsSeparatedByCharactersInSet: 
         [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]; 
    NSString* returnString = [Array componentsJoinedByString:@""]; 

    return (returnString); 

} 
+0

http://stackoverflow.com/a/1426819/944634 –

+0

我認爲這是最好的解決方案! – Stas

0

您可以使用stringByReplacingOccurrencesOfString: withString:刪除字符你不想如@"("@""

+0

這不是一個好主意.. – Stas

1

輸入:

NSString *[email protected]"(256) 435-8115"; 



NSArray *plainNumbersArray= 

[stringWithPhoneNumber componentsSeparatedByCharactersInSet: 

[[NSCharacterSet decimalDigitCharacterSet]invertedSet]]; 



NSString *plainNumbers = [plainNumbersArray componentsJoinedByString:@""]; 


NSLog(@"plain number is : %@",plainNumbers); 

輸出: 普通號碼是:2564358115