Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...