How do I determine if a char
in C such as a
or 9
is a number or a letter?
Is it better to use:
int a = Asc(theChar);
or this?
int a = (int)theChar
C isalpha() The isalpha() function checks whether a character is an alphabet or not. In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0.
isalnum() is a built-in Python function that checks whether all characters in a string are alphanumeric. In other words, isalnum() checks whether a string contains only letters or numbers or both. If all characters are alphanumeric, isalnum() returns the value True ; otherwise, the method returns the value False .
A char is not an object, so you can use equals() like you do for strings.
You'll want to use the isalpha()
and isdigit()
standard functions in <ctype.h>
.
char c = 'a'; // or whatever if (isalpha(c)) { puts("it's a letter"); } else if (isdigit(c)) { puts("it's a digit"); } else { puts("something else?"); }
chars are just integers, so you can actually do a straight comparison of your character against literals:
if( c >= '0' && c <= '9' ){
This applies to all characters. See your ascii table.
ctype.h also provides functions to do this for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With