简体   繁体   中英

Check if a letter is before or after another letter in C

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.

If your string is:

char str[10] = "Brad"

you can compare:

if (str[0]) < 't') {
    ...

which will evaluate to 1 (true) if 'B' is before the character 't' in the ASCII character set. Note that this comparison is case-sensitive, so you want to convert the characters that you are comparing to the same case for this to be meaningful. You can use the toupper() and tolower() functions from the ctype.h library to accomplish this. C treats char s as integer types, so you can perform mathematical operations with them.

Most introductory texts on C solve this problem the same way, but as @Olaf points out, the standard does not guarantee what values represent particular characters. So, when portability is a concern, you need to be more careful. That said, most systems use either ASCII or UTF-8, which is a superset of ASCII (they are identical for the first 128 characters), making this simple solution a reasonable place to start.

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

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