将字符A-Z转换为相应的整数。

5

我正在尝试将数组(第二个和第三个)槽中的字符转换为相应的整数值,例如A=1,B=2等等。对于A-Z。

我考虑采用if(x.charAt(i) == 'a'){ int z = 1; }这种方法来处理A-Z的所有情况,但我认为这是一种非常繁琐的方法。是否有一种更短的代码可以完成同样的事情?

public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];

for(int i=0; i<x.length();i++){
    arr[i] = x.charAt(i);
}


}

1
如果'A' == 1,那么'a'等于什么? - Jim Garrison
1
如果你正在使用ASCII字符,你可以做类似这样的事情:(int)Character.toUpperCase('A') - 64,它将等于1(或者(int)Character.toUpperCase(x.charAt(i)) - 64)。 - MadProgrammer
字符串将会是字符和整数的混合。我只需要将第二个和第三个字母转换为整数,因为之后需要进行计算。之后会添加忽略大小写的功能。 - LRZJohn
@MadProgrammer 谢谢。我使用了 int sec = (int)Character.toUpperCase(x.charAt(1)) - 64; - LRZJohn
@LRZJohn,我的下面的回答解决了你的问题,还是你需要其他的东西? - Achintya Jha
2个回答

4

试试这个:

arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;

你需要使用int数组而不是char数组。

public static void main(String[] args) {
    String x = "AbC";
    int[] arr = new int[x.length()];

    for (int i = 0; i < x.length(); i++) {
        arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;
    }
    System.out.println(Arrays.toString(arr));

}

输出:

[1, 2, 3]

3

由于您似乎不区分大小写,因此您可能希望先将字符串转换为大写或小写,但您需要考虑本地化:

// If you don't state a locale, and you are in Turkey,
// weird things can happen. Turkish has the İ character.
// Using lower case instead could lead to the ı character instead.
final String xu = x.toUpperCase(Locale.US);
for (int i = 0; i < xu.length(); ++i) {
    arr[i] = xu.charAt(i) - 'A' + 1;
}

另一种循环方式可以使用:

// Casing not necessary.
for (int i = 0; i < x.length(); ++i) {
    // One character
    String letter = x.substr(i, i+1);
    // A is 10 in base 11 and higher.  Z is 35 in base 36.
    // Subtract 9 to have A-Z be 1-26.
    arr[i] = Integer.valueOf(letter, 36) - 9;
}

这是应用偏执狂。我编辑了我的答案,指出你不需要改变我第二个选择中的大小写。 - Eric Jablow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接