Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 chars 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...