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);
}
}
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With