Convert char AZ to the corresponding int.

I am trying to convert an A char from an array of (2nd and 3rd) slots into an int value that matches, for example. A = 1, B = 2, etc. For AZ.

I think a long path will be executed if (x.charAt (i) == 'a') {int z = 1; } for all A - Z, which, in my opinion, is a very practical method. Is there a way that can do the same with shorter code?

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);
}


}
+5
source share
2 answers

Try the following:

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

Instead, you should use int Array instead of 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));

}

Conclusion:

[1, 2, 3]
+4
source

Since you do not seem to be compatible with the situation, you can first type in uppercase or lowercase strings, but you would like to know the locale:

// 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;
}

An alternative loop would use:

// 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;
}
+3
source

All Articles