Best way to convert English numbers to Arabic [duplicate]

柔情痞子 提交于 2019-11-27 18:35:16

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.

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() );

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!