Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char A-Z to corresponding int.

Tags:

java

arrays

i am trying to convert A char from an array (2nd and 3rd) slot to int value that correspond to eg. A = 1 , B= 2, etc. For A-Z.

I am thinking that the long way will be doing if(x.charAt(i) == 'a'){ int z = 1; } for the whole A - Z which i think it is a very practical method. Is there any method that can do the same thing with a 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);
}


}
like image 350
LRZJohn Avatar asked Apr 15 '13 04:04

LRZJohn


People also ask

How do I convert a char to an int in C#?

Use the Convert. ToInt32() Method to Convert char to int in C# The Convert. ToInt32() function, converts a specified value to a 32-bit signed integer.

How do I convert a char to a number in Java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How do you convert a char to an int in Python?

To convert Python char to int, use the ord() method. The ord() is a built-in Python function that accepts a character and returns the ASCII value of that character. The ord() method returns the number representing the Unicode code of a specified character.


1 Answers

Try this:

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

You have to use int Array instead 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));

}

Output:

[1, 2, 3]
like image 67
Achintya Jha Avatar answered Sep 18 '22 20:09

Achintya Jha