tags:

views:

173

answers:

3

So you have Table mapping the 26 ascii characters from the English alphabet to their corresponding morse code strings

typedef struct a_look_tab {
    char table[asciiNum][MORSE_MAX+1]; 

} ALookTab;

and asciiNum is the 0 for a, 1 for b, and so on. how to return an index (int) that is the index of the morse char.

So what we are doing after converting a char into a number is to param ascii The ascii character to convert and return The index for the given ascii character, how do we do that?

+2  A: 

You need to convert a character, such as 'a', into its index in the table. According to your specification, the table begins with the Morse code for 'a', so 'a' should map to the index 0, 'b' should map to 1, and so on.

The simplest such mapping could be implemented like this:

int char_to_index(char c)
{
  return tolower(c) - 'a';
}

This subtracts the ASCII code for 'a' from the given letter, which will turn 'a' into 0, and so on.

Unfortunately, this only works if the computer running the program encodes the letters of the alphabet using a system that assigns contiguous codes to the letters. Not all computers are like this. A more portable function could do the mapping explicitly, like so:

int char_to_index2(char c)
{
  switch(tolower(c))
  {
  case 'a': return 0;
  case 'b': return 1;
  case 'c': return 2;
  /* and so on */
  }
}

This is more verbose code-wise, but more portable.

UPDATE: I added calls to tolower() to both functions to make them a bit more robust.

unwind
For the record, I'd `switch(tolower(c))` but that's just because I like case-insensitivity (capital K is rather sensitive about its case).
Chris Lutz
@Chris: Agreed. I aimed for maximum transparency/simplicity, but a call to tolower() isn't too much to ask for. :) Thanks!
unwind
+2  A: 

Note that the C standard doesn't require ASCII, and this code won't work under EBCDIC, but 99% of the time this won't matter.

I believe what you're looking for is much simpler than you think. Character literals like 'c' and '0' are actualy ints, not chars - they're casted down to char at assignment, and can be just as easily cast back up. So this is what (I think) you want:

#include <ctype.h> // for tolower()

char *func(ALookTab *a, char c)
{
    if(isalpha(c))
        return a->table[tolower(c) - 'a'];
    if(isdigit(c))
        return a->table[c - '0' + 26];
    // handle special characters
}

Note that this code assumes that your morse code is stored as the 26 alphabet characters, the 10 digits, and then other special characters in whatever order you choose.

Chris Lutz
+3  A: 

The simplest portable way to convert the char to an index is this type of construction:

/* Returns -1 if c is not an upper- or lower-case alphabetical character */
int char_to_index(char c)
{
    static const char * const alphabet = "abcdefghijklmnopqrstuvwxyz";
    char *p = strchr(alphabet, tolower((unsigned char)c));

    return p ? p - alphabet : -1;
}
caf