如何将非英语数字转换为英文数字,如: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);
}
Run Code Online (Sandbox Code Playgroud)
Anb*_*hik 19
喜欢
let NumberStr: String = "????-??-??"
let Formatter = NumberFormatter()
Formatter.locale = NSLocale(localeIdentifier: "EN") as Locale!
if let final = Formatter.number(from: NumberStr) {
print(final)
}
Run Code Online (Sandbox Code Playgroud)
产量
替代方式
选项2
extension String {
public var arToEnDigits : String {
let arabicNumbers = ["?": "0","?": "1","?": "2","?": "3","?": "4","?": "5","?": "6","?": "7","?": "8","?": "9"]
var txt = self
arabicNumbers.map { txt = txt.replacingOccurrences(of: $0, with: $1)}
return txt
}
}
Run Code Online (Sandbox Code Playgroud)
Hos*_*eeb 17
使用的问题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"
Run Code Online (Sandbox Code Playgroud)
小智 5
要将上述代码用作函数,请尝试以下操作:
func toEnglishNumber(number: String) -> NSNumber {
var result:NSNumber = 0
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "EN")
if let finalText = numberFormatter.number(from: number)
{
print("Intial text is: ", number)
print("Final text is: ", finalText)
result = finalText
}
return result
}
Run Code Online (Sandbox Code Playgroud)
要使用该功能:
print(toEnglishNumber(number: "??"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8751 次 |
| 最近记录: |