在Swift中将阿拉伯字符串转换为英文数字

时间:2016-08-12 18:01:40

标签: ios swift

如何将非英语数字转换为英文数字,​​如: 斯威夫特的“3486912881”到“3486912881” 或者我想接受英文数字并获得其他人。

在Java Android中,这段代码对我有用:

private static String arabicToDecimal(String number) {
    char[] chars = new char[number.length()];
    for(int i=0;i<number.length();i++) {
        char ch = number.charAt(i);
        if (ch >= 0x0660 && ch <= 0x0669)
           ch -= 0x0660 - '0';
        else if (ch >= 0x06f0 && ch <= 0x06F9)
           ch -= 0x06f0 - '0';
        chars[i] = ch;
    }
    return new String(chars);
}

5 个答案:

答案 0 :(得分:17)

喜欢

     let NumberStr: String = "٢٠١٨-٠٦-٠٤"
    let Formatter = NumberFormatter()
    Formatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
    if let final = Formatter.number(from: NumberStr) {
        print(final)

    }

<强>输出

enter image description here

替代方式

选项2

let arabicNumbers = [
        "٠": "0",
        "١": "1",
        "٢": "2",
        "٣": "3",
        "٤": "4",
        "٥": "5",
        "٦": "6",
        "٧": "7",
        "٨": "8",
        "٩": "9"
    ]
    var getOp = "٢٠١٨-٠٦-٠٤"
    for (key,value) in arabicNumbers {
        getOp = getOp.replacingOccurrences(of: key, with: value)
    }
    print("getOp == \(getOp)")  

答案 1 :(得分:16)

使用NumberFormatter的问题在于它会忽略其他非数字字符,例如,如果您有Hello ١٢٣它将是123。要保留其他字符并仅转换数字,可以使用以下内容:

public extension String {

public var replacedArabicDigitsWithEnglish: String {
    var str = self
    let map = ["٠": "0",
               "١": "1",
               "٢": "2",
               "٣": "3",
               "٤": "4",
               "٥": "5",
               "٦": "6",
               "٧": "7",
               "٨": "8",
               "٩": "9"]
    map.forEach { str = str.replacingOccurrences(of: $0, with: $1) }
    return str
}
}

/// usage

"Hello ١٢٣٤٥٦٧٨٩١٠".replacedArabicDigitsWithEnglish // "Hello 12345678910"

答案 2 :(得分:2)

对于Swift 3.0或更高版本:

let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "EN")
    if let finalText = numberFormatter.number(from: "text here")
    {
      print("Final text is: ", finalText)
    }

答案 3 :(得分:2)

要将上述代码用作功能,请尝试以下操作:

 print(toEnglishNumber(number: "١٢"))

使用此功能:

Menu.buildFromTemplate(mainMenu.object)

答案 4 :(得分:0)

我认为最简单,最Swifty的方式是使用compactMap

//this code is for Persian numbers, but you can easily change number dictionary values to arabic numbers.

    extension String {

        func convertToPersianNum() -> String {
            let numbers:[Character : Character] = ["1":"۱","2":"۲","3":"۳","4":"۴","5":"۵","6":"۶","7":"۷","8":"۸","9":"۹","0":"۰"]

            let converted = String(self.compactMap{numbers[$0]})

            return converted

        }

    }


    "123456".convertToPersianNum() //۱۲۳۴۵۶