我正在尝试将一个char从一个数组(第二和第三个)槽转换为对应于例如的int值。 A = 1,B = 2等。对于A-Z。
我在想,如果(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);
}
}
答案 0 :(得分:4)
试试这个:
arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;
你必须使用int Array而不是char Array。
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]
答案 1 :(得分: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;
}