"C" Progrmming Language - Characters and Strings

Started by sivaji, Jan 10, 2008, 07:02 PM

Previous topic - Next topic

sivaji

Programming Stuffs in "C" - Technical Skills for INTERVIEW

Characters and Strings


1: How can I get the numeric (character set) value corresponding to a character, or vice versa?

The obvious way is to write a function to do the conversion. (Error checking has been omitted for brevity.)
int ctoi(char c) {
   static unsigned char *ary;
   /* initialize the array */
   if (!ary) {
      int i;

      ary = malloc(UCHAR_MAX + 2);
      for (i = 0; i < UCHAR_MAX + 1; ++i) {
         ary = i;
      }
      ary[UCHAR_MAX + 1] = '\0';
   }
   if (c) {
      unsigned char *t;

      /* we have to skip the leading NUL */
      t = strchr(ary + 1, c);
      if (!t)
         return 0;
      return t - ary;
   } else {
      /* special case for NUL character */
      return 0;
   }
}

There are various clever tricks you can use to get around writing the function, but most are too complicated for beginners.
Am now @ Chennai