13

在我的应用程序中,我有一个字符串,例如:

“3022513240”

我想这样转换:

(302)-251-3240

我该如何解决这个问题?

4

11 回答 11

13

这是一个 Swift 扩展,它将字符串格式化为 10 位数字的电话号码。

extension String {    
    public func toPhoneNumber() -> String {
        return stringByReplacingOccurrencesOfString("(\\d{3})(\\d{3})(\\d+)", withString: "($1) $2-$3", options: .RegularExpressionSearch, range: nil)
    }
}

例如:

let number = "1234567890"
let phone = number.toPhoneNumber()
print(phone)
// (123) 456-7890

更新到 Swift 3.0

extension String {
    public func toPhoneNumber() -> String {
        return self.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1) $2-$3", options: .regularExpression, range: nil)
    }
}
于 2015-12-08T22:34:33.977 回答
11

我会这样做:

例子:

 NSMutableString *stringts = [NSMutableString stringWithString:self.ts.text];
 [stringts insertString:@"(" atIndex:0];
 [stringts insertString:@")" atIndex:4];
 [stringts insertString:@"-" atIndex:5];
 [stringts insertString:@"-" atIndex:9];
 self.ts.text = stringts;

希望这可以帮助...

于 2013-02-20T07:49:23.317 回答
2

你可以使用这种方式

NSError *aError = nil;
NBPhoneNumber *myNumber1 = [phoneUtil parse:@"6766077303" defaultRegion:@"AT" error:&aError];
if (aError == nil)
{
    NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber1] ? @"YES":@"NO");
    NSLog(@"E164          : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatE164]);
    NSLog(@"INTERNATIONAL : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatINTERNATIONAL]);
    NSLog(@"NATIONAL      : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatNATIONAL]);
    NSLog(@"RFC3966       : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatRFC3966]);
}
else
{
    NSLog(@"Error : %@", [aError localizedDescription]);
}
于 2013-02-25T06:05:25.433 回答
2

斯威夫特 4.2

extension String {
public func toPhoneNumber() -> String {
    return self.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "$1-$2-$3", options: .regularExpression, range: nil)
}}

结果

结果

于 2019-03-19T16:26:27.203 回答
2

斯威夫特 4.2

处理 10 位和 11 位电话号码,这些电话号码在字符串中可能已经或可能没有格式或非数字字符。

将处理:

  • 1234567890, 12345678901, 123 456 7890, 123-456-7890, (123) 456-7890, 1-234-567-8901

结果:

  • (999)-999-9999
  • 1(999)-999-9999

代码:

extension String {

    /// Handles 10 or 11 digit phone numbers
    ///
    /// - Returns: formatted phone number or original value
    public func toPhoneNumber() -> String {
        let digits = self.digitsOnly
        if digits.count == 10 {
            return digits.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1)-$2-$3", options: .regularExpression, range: nil)
        }
        else if digits.count == 11 {
            return digits.replacingOccurrences(of: "(\\d{1})(\\d{3})(\\d{3})(\\d+)", with: "$1($2)-$3-$4", options: .regularExpression, range: nil)
        }
        else {
            return self
        }
    }

}

extension StringProtocol {

    /// Returns the string with only [0-9], all other characters are filtered out
    var digitsOnly: String {
        return String(filter(("0"..."9").contains))
    }

}

例子:

let num = "1234567890"
let formatted = num.toPhoneNumber()
// Formatted is "(123)-456-7890"
于 2019-07-09T13:48:28.407 回答
1

您可以使用正则表达式(\d{3})(\d{3})(\d{4})并将匹配模式的输入替换为($1)-$2-$3

于 2013-02-20T07:23:02.940 回答
0

您可以使用RMPhoneFormat库来格式化电话号码。格式应该复制您在联系人应用程序中看到的相同电话号码的内容。

于 2013-02-20T07:32:11.683 回答
0

这是简单易行的

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if (string.length) {
       if (textField.text.length<=13) {
           if (textField.text.length==3) {
               NSString *tempStr=[NSString stringWithFormat:@"(%@)- ",textField.text];
               textField.text=tempStr;
           } else if (textField.text.length==8) {
               NSString *tempStr=[NSString stringWithFormat:@"%@-",textField.text];
               textField.text=tempStr;
           }
       } else {
           return NO;
       }
   }
   return YES;
}
于 2014-02-20T09:27:51.407 回答
0

我用SHSPhoneNumberFormatter来做到这一点,所以我不必更改我的类型或子类UITextField

要设置它:

let phoneNumberFormatter = SHSPhoneNumberFormatter()
phoneNumberFormatter.setDefaultOutputPattern("(###) ###-####")

监听UITextFieldTextDidChangeNotification并运行以下命令:

let phoneDict = phoneNumberFormatter.valuesForString(phoneTextField.text) 
phoneTextField.text = phoneDict["text"] as? String
于 2016-03-23T22:05:37.197 回答
0

查找RMPhoneFormat,我用它很棒。

于 2015-09-04T19:18:43.997 回答
0

Here is a code to convert string to phone number format

Swift 3

func PhoneNumberFormate( str : NSMutableString)->String{
        str.insert("(", at: 0)
        str.insert(")", at: 4)
        str.insert("-", at: 8)
        return str as String
    }

to use

let nsMutableString = NSMutableString(string: "3022513240")
let strModify = self.PhoneNumberFormate(str: nsMutableString)
于 2017-03-23T10:35:31.387 回答