REA98
REA98

Reputation: 63

Converting Char to its Numerical value without using getNumericValue

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

Upvotes: 4

Views: 159

Answers (3)

Eran
Eran

Reputation: 393811

Well, if you want to map 'a' to 'z' to the numbers 1 to 26, you can subtract 'a' and add 1 :

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

EDIT :

In order to convert all the characters of some input String to integers, you can use an array to store the integer values.

For example :

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

Upvotes: 3

Tamim Anwar Chowdhury
Tamim Anwar Chowdhury

Reputation: 83

Try this.

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

  int integerValue = (int) character;

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

  integerValue = integerValue - (int) subtract + 1;

  return integerValue;
}

Upvotes: 1

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You could just use a simple artithmetic operation

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

This will also work since

`

is the character before a in the ASCII table

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

UpperCase / LowerCase

The following works for either lowercase or uppercase characters

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

Upvotes: 2

Related Questions