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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…