21

Possible Duplicate:
Convert String to another locale in java

I want to convert a java String that contains english numbers to arabic one's so i make this

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 ?

Community
  • 1
  • 1
confucius
  • 13,127
  • 10
  • 47
  • 66

2 Answers2

41

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() );
Zéychin
  • 4,135
  • 2
  • 28
  • 27
  • 2
    I can not get the Arabic numbers to display in the right direction on Stackoverflow. They should be from `٠` to `٩`, not from `٩` to `٠`. – Zéychin Jul 13 '12 at 11:32
  • 7
    Persian chars would be 'char[] persianChars = {'۰', '۱', '۲', '٣', '۴', '۵', '۶', '۷', '۸', '٩'};' – Milad Faridnia May 02 '16 at 06:06
  • 1
    looks great and I use it in my project but i don't know why it throw ArrayIndexOutOfBoundsException – Mohamed Ibrahim Oct 05 '16 at 09:14
  • This works well, if you like also, you can add the Arabic comma to `arabicChars` array so it can be replaced when you have a number with double or float format. I will edit the answer. – blueware Oct 26 '16 at 13:14
  • http://stackoverflow.com/questions/5316131/convert-string-to-another-locale-in-java doesn't throw ArrayIndexOutOfBoundsException – amorenew Apr 05 '17 at 11:38
  • The solution works very well but screwed in decimals. – Bibin Zacharias Oct 07 '19 at 07:06
1

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.

infiniteRefactor
  • 1,940
  • 15
  • 22