Question

I have a problem, I need to relate a value to a letter. The values come in an array. For example:

Value vector -> [1,2,3,1,2,5,1,...,8]

I need an idea to make the first number of that vector be linked to the letter "a", the 2nd number to the letter "b", etc until the last number to the letter "z".

So, a -> 2, value of "a" is 2.

The purpose of this is if I have a word like "air" I want the value of air to be the value of "a" + the value of "i" + the value of "r".

Was it helpful?

Solution

Your problem seems to be that you can't get the array index from a letter. The twenty-six lowercase Latin letters are a contiguous block in ASCII, and you can get the ASCII code of a character with the single-quote notation, hence:

int ix = c - 'a'

Note that this will give you invalid indices for your array if your character c is not a letter. If your alphabet is not the plain Latin alphabet, you could write a function to assign a numerical index to your letter. For example, if I wanted to write an index function for the German alphabet, I would do something like this:

int index_de(int c) {
    if (c == 'ä') return 26;
    if (c == 'ö') return 27;
    if (c == 'ü') return 28;
    if (c == 'ß') return 29;
    if (c < 'a' || c > 'z') return -1;
    return c - 'a';
}

(Because the accented letters are outside the pure 7-bit ASCII range, this will introduce issues of source-code and input encoding. Be warned.)

You can then use this function to assign scores to letter codes when you (a) read the file and then (b) scan the words you want to score.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top