0

I would like to check if the first letter of a string is before or after the letter t in the alphabet.

For example, the user inputs "Brad" and it would print

"Your name starts with a letter that comes before "t"."

Something of that sort.

user6720691
  • 55
  • 1
  • 8
  • if your input is in variable In, you can check it like this `if (In[0] < 't')` – Prasanna Oct 07 '16 at 03:20
  • Hint: remember that characters are really numbers, for example capitol A, 'A' is 0x41. With that in mind, take a look at the ASCII character table (see http://www.asciitable.com/) and see if you can't think of a way to determine that 'B' (0x42) comes before t (0x74). – thurizas Oct 07 '16 at 03:21
  • But beware of the fact that there can be upper and lower cases. For that just convert everything to upper or lower before comparing – Prasanna Oct 07 '16 at 03:21
  • There is no guarantee letters have adjascent codes or even alphabetically ordered. It depends on your execution character set. – too honest for this site Oct 07 '16 at 13:08

1 Answers1

0

Something like below (add checks for null and if it the first character is t itself, etc).

#include <stdio.h>
#include <stdlib.h>

/* t's value in ASCII */
#define LETTER_T 116

int main(int argc, char * argv[])
{
      /* Use toupper or tolower functions to handle casing */
      char * str = "brad"; 
      char * result = (str[0] < LETTER_T) ? "before" : "after";
      printf("%s starts with a %c that comes %s the letter t.", str, str[0], result);
      return 0;
}
lolololol ol
  • 848
  • 1
  • 8
  • 18
  • 1
    There is no guarantee letters have adjascent codes or even alphabetically ordered. It depends on your execution character set. – too honest for this site Oct 07 '16 at 13:08
  • @Olaf This was meant to be a simple example, not a robust solution taking into account different character sets than ASCII (i.e. Unicode, UTF-8, etc). The answer is even qualified by 'something like below'. – lolololol ol Oct 07 '16 at 17:01
  • 1
    That does not even imply the solution can be completely off (as it would be for e.g. EBCDIC). Btw. using magic numbers is a no-go. Any reason you don't use the integer `'t'`? – too honest for this site Oct 07 '16 at 17:03