java 在java中将String转换为另一个语言环境

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5316131/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:35:43  来源:igfitidea点击:

Convert String to another locale in java

javalocale

提问by RYN

Hi
I need to convert Arabic/Persian Numbers to it's English equal (for example convert "?" to "2")
How can I do this?

嗨,
我需要将阿拉伯/波斯数字转换为英语相等(例如将“?”转换为“2”)
我该怎么做?

Thanks

谢谢

回答by Peter Lawrey

I suggest you have a ten digit lookup String and replace all the digits one at a time.

我建议你有一个十位数的查找字符串并一次替换所有数字。

public static void main(String... args) {
    System.out.println(arabicToDecimal("??"));
}

private static final String arabic = "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9";
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);
}

prints

印刷

42

The reason for using the strings as a lookup is that other characters such as .-,would be left as is. In fact a decimal number would be unchanged.

使用字符串作为查找的原因是其他字符(例如).-,将保持原样。事实上,十进制数将保持不变。

回答by Navas Basheer

I achived this by java.math.BigDecimalClass, Below is the code snippet

我通过java.math.BigDecimal类实现了这一点,下面是代码片段

String arabicNumerals = "????.??";
String englishNumerals = new BigDecimal(arabic).toString();
System.out.println("Number In Arabic : "+arabicNumerals);
System.out.println("Number In English : "+englishNumerals);

Result

结果

Number In Arabic : ????.??
Number In English : 4242.42

NB :The Above code will not work if there is any charactors other than numeric digits in arabicNumerals, For Eg : ?,???.?? will result in java.lang.NumberFormatException, so you may remove other charactors using Character.isDigit(char ch)in another logic and use the above code. All normal cases are working charmly !!

注意:如果 arabicNumerals 中有数字以外的任何字符,则上述代码将不起作用,例如:?,???.?? 将导致java.lang.NumberFormatException,因此您可以删除其他Character.isDigit(char ch)逻辑中使用的其他字符并使用上述代码。所有正常情况下都可以正常工作!!

Good Day

再会

回答by Kishath

I found a simpler and faster way which includes the two arabic code pages too.

我找到了一种更简单快捷的方法,其中也包括两个阿拉伯语代码页。

public static String convertToEnglishDigits(String value)
{
     String newValue = value.replace("?", "1").replace("?", "2").replace("?", "3").replace("?", "4").replace("?", "5")
             .replace("?", "6").replace("7", "?").replace("?", "8").replace("?", "9").replace("?", "0")
             .replace("?", "1").replace("?", "2").replace("?", "3").replace("?", "4").replace("?", "5")
             .replace("?", "6").replace("?", "7").replace("?", "8").replace("?", "9").replace("?", "0");

     return newValue;
}

It will return the numbers in English format or vise versa if you change the replace from.
("?", "0") to ("0","?")

如果您更改替换,它将以英文格式返回数字,反之亦然。
("?", "0") 到 ("0","?")

回答by Sileria

Try this guys:

试试这个家伙:

/**
 * Utility class to detect arabic languages and convert numbers into arabic digits.
 *
 * @author Ahmed Shakil
 * @date 09-24-2012
 */
public final class ArabicUtil {

private static final char[] DIGITS = {'\u0660','\u0661','\u0662','\u0663','\u0664','\u0665','\u0666','\u0667','\u0668','\u0669'};

/**
 * Returns <code>true</code> if the provided language code uses arabic characters; othersise <code>false</code>.
 * @param lang ISO language code.
 * @return <code>true</code> if the provided language code uses arabic characters; othersise <code>false</code>
 */
public static boolean isArabic (String lang) {
    return "ar".equals(lang) || "fa".equals(lang) || "ur".equals(lang);
}

/**
 * Convert digits in the specified string to arabic digits.
 */
public static String convertDigits (String str) {
    if (str == null || str.length() == 0) return str;

    char[] s = new char[str.length()];
    for(int i =0;i<s.length;i++)
        s[i] = toDigit( str.charAt( i ) );

    return new String(s);
}

/**
 * Convert single digit in the specified string to arabic digit.
 */
public static char toDigit (char ch) {
    int n = Character.getNumericValue( (int)ch );
    return n >=0 && n < 10 ? ARABIC[n] : ch;
}

/**
 * Convert an int into arabic string.
 */
public static String toString (int num) {
    return convertDigits( Integer.toString( num ) );
}
}

BTW there is a difference between arabic digits vs. urdu/farsi: Arabic:

顺便说一句,阿拉伯数字与乌尔都语/波斯语之间存在差异:阿拉伯语:

private static final char[] ARABIC     = {'\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'};

Urdu or Farsi:

乌尔都语或波斯语:

private static final char[] URDU_FARSI = {'\u06f0', '\u06f1', '\u06f2', '\u06f3', '\u06f4', '\u06f5', '\u06f6', '\u06f7', '\u06f8', '\u06f9'};

回答by Tomasz Nurkiewicz

First make it work, then make it look nice ;-)

首先让它工作,然后让它看起来不错;-)

public static char persianDigitToEnglish(char persianDigit) {
    return (char) (((int)persianDigit) - ((int)'?' - (int)'2'));
}

Works for 2, unfortunately I don't know other Persian digits, could You give it a try?

适用于2,不幸的是我不知道其他波斯数字,您可以尝试一下吗?

assertThat(persianDigitToEnglish('?')).isEqualTo('2');

EDIT: (based on Peter LawreyString version, but uses StringBuilder)

编辑:(基于Peter LawreyString 版本,但使用StringBuilder

public static String persianDigitToEnglish(String persianNumber) {
    StringBuilder chars = new StringBuilder(persianNumber.length());
    for (int i = 0; i < persianNumber.length(); i++)
        chars.append(persianDigitToEnglish(persianNumber.charAt(i)));
    return chars.toString();
}

private static char persianDigitToEnglish(char persianDigit) {
    return (char) (((int)persianDigit) - ((int)'?' - (int)'2'));
}

回答by sujith s

it will work with decimal point also ..

它也适用于小数点..

public class mainsupport {
public static void main(String args[]){
//  String Numtoconvert="15.3201" ;
//  String Numtoconvert="458" ;
    String Numtoconvert="??????" ; // integer value 87.598

      System.out.println(getUSNumber(Numtoconvert));
}
private static String getUSNumber(String Numtoconvert){

    NumberFormat formatter = NumberFormat.getInstance(Locale.US);
      try {
          if(Numtoconvert.contains("?"))      
          Numtoconvert=formatter.parse(Numtoconvert.split("?")[0].trim())+"."+formatter.parse(Numtoconvert.split("?")[1].trim());
          else
              Numtoconvert=formatter.parse(Numtoconvert).toString();
      } catch (ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      return Numtoconvert;
}

prints 87.598

打印 87.598

回答by Mehdi Khademloo

so trivial answer:

如此琐碎的答案:

public static String convertNumbersToPersian(String str)
{
    String answer = str;
    answer = answer.replace("1","?");
    answer = answer.replace("2","?");
    answer = answer.replace("3","?");
    answer = answer.replace("4","?");
    answer = answer.replace("5","?");
    answer = answer.replace("6","?");
    answer = answer.replace("7","?");
    answer = answer.replace("8","?");
    answer = answer.replace("9","?");
    answer = answer.replace("0","?");
    return answer;
}

and

public static String convertNumbersToEnglish(String str) {
    String answer = str;
    answer = answer.replace("?", "1");
    answer = answer.replace("?", "2");
    answer = answer.replace("?", "3");
    answer = answer.replace("?", "4");
    answer = answer.replace("?", "5");
    answer = answer.replace("?", "6");
    answer = answer.replace("?", "7");
    answer = answer.replace("?", "8");
    answer = answer.replace("?", "9");
    answer = answer.replace("?", "0");
    return answer;
}

回答by Sepehr Nozaryian

i think the best way is to change the Locale to what you want for example,
for double number :

我认为最好的方法是将 Locale 更改为您想要的,例如,
对于 double number :

NumberFormat fmt = NumberFormat.getNumberInstance(Locale.US);
d = Double.parseDouble(s);

for String :

对于字符串:

NumberFormat.getNumberInstance(Locale.US).format(s);

or DecimalFormat:

或十进制格式:

double num;
DecimalFormat df = new DecimalFormat("###.###");
df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
String s = df.format(num);

回答by Flovettee

Character.getNumericValue(ch)saved my life, generic solution for any locale.

Character.getNumericValue(ch)挽救了我的生命,适用于任何语言环境的通用解决方案。

static String replaceNonstandardDigits(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (Character.isDigit(ch) && !(ch >= '0' && ch <= '9')) {
            int numericValue = Character.getNumericValue(ch);
            if (numericValue >= 0) {
                builder.append(numericValue);
            }
        } else {
            builder.append(ch);
        }
    }
    return builder.toString();
}

回答by Hend

Use Locale class to convert numbers.

使用 Locale 类来转换数字。

 Locale locale = new Locale("ar");
 String formattedArabic = format(locale, "%d", value));