1

So, what I need to do is translate an array of chars into an array of numbers.

I know this sounds like an odd request, but here's what I've been trying to do:

Have an array like this:

charArray[0] = e;
charArray[1] = b;
charArray[2] = p;

and have it translatated into:

numArray[0] = 5;
numArray[1] = 2;
numArray[2] = 16;

So it would translate the char into it's position in the alphabet (eg. "a" is the 1st letter, "b" is the 2nd, etc)

What's the best way of doing this? I was going to attempt to do it one by one, but then realized I would have way too many lines of code, it would just be tons of nested if statements, and I figured there's probably some better way to do it.

(My way was going to be if charArray[0] = a then numArray[0] = 1, and go through every single letter like that, until you get to if charArray[0] = z then numArray[0] = 26, but that would require 26 different if statements PER CHAR in the char array, which would be a horrible way of doing it in my opinion, because my char array is extremely long.)

3 Answers 3

7

You can use a trick For each index i:

numArray[i] = charArray[i] - 'a' + 1;

A more "by the book" way of doing it is:

final String letters = "abcdefghijklmnopqrstuvwxyz";
. . .
numArray[i] = letters.indexOf(charArray[i]) + 1;

Then any positions i such that charAray[i] is not a lower-case letter will end up as 0 in numArray[i]. With the trick, the value of numArray[i] will be something unpredictable.

Sign up to request clarification or add additional context in comments.

Comments

1

You can simply:

numArray[i] = charArray[i] - 'a' + 1;

Explanation:

Looking at the ascci table you'll see the decimal value of each char.

a has the decimal value of 97. So you remove 97 from it and add 1. You get 1.

The same for b...z, removing 97 (a) from 98 (b) will be 1, and you add 1 to get 2.. and so on..

Comments

0

Assume all characters are lowercase, you can write:

numArray[0]  = (charArray[0] - 'a' + 1);

If you have lowercase and uppercase, you can use an if statement like:

if (charArray[0] >= 'A' && charArray[0] <= 'Z') {
  numArray[0]  = (charArray[0] - 'A' + 1);
} else {
  numArray[0]  = (charArray[0] - 'a' + 1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.