繁体   English   中英

将带字母的字符串数组转换为java中的int数组

[英]converting a string array with letters into an int array in java

好的我将尝试在这里解释我的问题,我需要做的是将字符串数组转换为int数组。

这是我的一部分(初始设置)

   System.out.println("Please enter a 4 digit number to be converted to decimal ");
    basenumber = input.next();

    temp = basenumber.split("");
    for(int i = 0; i < temp.length; i++)
        System.out.println(temp[i]);

    //int[] numValue = new int[temp.length];
    ArrayList<Integer>numValue = new ArrayList<Integer>();

    for(int i = 0; i < temp.length; i++)
        if (temp[i].equals('0')) 
            numValue.add(0);
        else if (temp[i].equals('1')) 
            numValue.add(1);
                     ........
        else if (temp[i].equals('a') || temp[i].equals('A'))
            numValue.add(10);
                     .........
             for(int i = 0; i < numValue.size(); i++)
        System.out.print(numValue.get(i));

基本上我要做的是将0-9设置为实际数字,然后从输入字符串(例如Z3A7)开始将az设置为10-35,理想情况下将打印为35 3 10 7

在循环中尝试这个:

Integer.parseInt(letter, 36);

这将把letter解释为base36号码(0-9 + 26个字母)。

Integer.parseInt("2", 36); // 2
Integer.parseInt("B", 36); // 11
Integer.parseInt("z", 36); // 35

您可以在循环中使用此单行(假设用户不输入空字符串):

int x = Character.isDigit(temp[i].charAt(0)) ?
        Integer.parseInt(temp[i]) : ((int) temp[i].toLowerCase().charAt(0)-87) ;

numValue.add( x );

上面代码的解释:

  • temp[i].toLowerCase() => z和Z将转换为相同的值。
  • (int) temp[i].toLowerCase().charAt(0) => 字符的ASCII码。
  • -87 =>根据您的规范减去87。

考虑到你想把Z表示为35,我写了以下函数

更新:

Z的ASCII值为90,因此如果要将Z表示为35,则应将55中的每个字符减去(90-35 = 55):

public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
    if (sarray != null) {
        int intarray[] = new int[sarray.length];
        for (int i = 0; i < sarray.length; i++) {
            if (sarray[i].matches("[a-zA-Z]")) {
                intarray[i] = (int) sarray[i].toUpperCase().charAt(0) - 55;
            } else {
                intarray[i] = Integer.parseInt(sarray[i]);
            }
        }
        return intarray;
    }
    return null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM