简体   繁体   中英

How to return the index of ascii char in C

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?

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

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.

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 int s, not char s - 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM