Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if char is a num or letter

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 
like image 999
Mona Avatar asked Dec 23 '11 02:12

Mona


People also ask

How do you check if a char is a letter in C?

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.

How do you check if a character is a number or letter in Python?

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 .

Do you use == or .equals for char?

A char is not an object, so you can use equals() like you do for strings.


2 Answers

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?"); } 
like image 180
Greg Hewgill Avatar answered Oct 25 '22 03:10

Greg Hewgill


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.

like image 28
Christopher Neylan Avatar answered Oct 25 '22 04:10

Christopher Neylan