java 将英文数字转换为阿拉伯数字的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11469058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to convert English numbers to Arabic
提问by confucius
Possible Duplicate:
Convert String to another locale in java
可能的重复:
将字符串转换为 Java 中的另一个语言环境
I want to convert a java
String
that contains english numbers to arabic one's so i make this
我想将一个java
String
包含英文数字的数字转换为阿拉伯数字,所以我做了这个
int arabic_zero_unicode= 1632;
String str = "13240453";
StringBuilder builder = new StringBuilder();
for(int i =0; i < str.length(); ++i ) {
builder.append((char)((int)str.charAt(i) - 48+arabic_zero_unicode));
}
System.out.println("Number in English : "+str);
System.out.println("Number In Arabic : "+builder.toString() );
the out put
输出
Number in English : 13240453
Number In Arabic : ????????
is there another more efficient way to do this ?
有没有另一种更有效的方法来做到这一点?
回答by Zéychin
This gives a 5x speedup over your version with a string of length 3036. This also checks to make sure you're only changing digits. It's about a 6x speedup without the if/else check.
这与长度为 3036 的字符串的版本相比,速度提高了 5 倍。这还会检查以确保您只更改数字。在没有 if/else 检查的情况下,这大约是 6 倍的加速。
Please pardon me if the characters are incorrect/misplaced. I had to find some of them from another source.
如果字符不正确/放错位置,请原谅我。我不得不从另一个来源找到其中的一些。
char[] arabicChars = {'?','?','?','?','?','?','?','?','?','?'};
StringBuilder builder = new StringBuilder();
for(int i =0;i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
{
builder.append(arabicChars[(int)(str.charAt(i))-48]);
}
else
{
builder.append(str.charAt(i));
}
}
System.out.println("Number in English : "+str);
System.out.println("Number In Arabic : "+builder.toString() );
回答by infiniteRefactor
There are a couple of Java classes that you can utilize to accomplish this in a high level fashion without explicit assumptions on Unicode table structure. For example you can check out DecimalFormatSymbols. However the idea will be the same as the code sample you've provided. The locale conversion methods or classes in Java library will only render the way numbers are displayed, they do not convert numeral symbols in a trivial way.
您可以使用几个 Java 类以高级方式完成此操作,而无需对 Unicode 表结构进行明确假设。例如,您可以查看DecimalFormatSymbols。但是,该想法与您提供的代码示例相同。Java 库中的语言环境转换方法或类只会呈现数字的显示方式,它们不会以琐碎的方式转换数字符号。