Convert Char to its numeric value without using getNumericValue

Is there any algorithm that could replace getNumericValue with converting a character to its numeric value, such as 'a' = 1 'b' = 2 and so on? Thank you in advance!

+4
source share
3 answers

Well, if you want to match 'a' with 'z' with numbers from 1 to 26, you can subtract 'a' and add 1:

char c = 'e';
int nc = c - 'a' + 1; // 5

EDIT:

To convert all characters of a given input string to integers, you can use an array to store integer values.

For instance:

String input = "over";
int[] numbers = input.length();
for (int i=0; i<input.length(); i++)
    numbers[i] = input.charAt(i) - 'a' + 1;
System.out.println(Arrays.toString(numbers));
+3
source

You can just use a simple arithmetic operation

char d = 'd';
int numericValue = d - 'a' + 1; // 4

`

- a ASCII

int numericValue = d - '`'; // 4

UpperCase/LowerCase

char d  = 'd';
int numericValue = d - (d > 96 ? '`' : '@');
+2

.

  int intVal(char character){
  char subtract = 'a';

  int integerValue = (int) character;

  if(integerValue < 97){
    subtract = 'A';
  }

  integerValue = integerValue - (int) subtract + 1;

  return integerValue;
}
+1
source

All Articles