C Character Functions
Character Functions
When you create a password on a website, it often checks the characters you type: Is there a digit? Is there an uppercase letter?
In C, you can check and change single characters with the character functions in the <ctype.h> header file. To use them, include the header in your program:
#include <ctype.h>
For example, isdigit() checks if a character is a digit (0 to 9):
Example
char c = '7';
if (isdigit(c)) {
printf("%c is a digit\n", c);
}
Try it Yourself »
The functions that check a character return a non-zero value (true) if the answer is yes, and 0 (false) if not. That is why you can use them directly in an if statement.
Check Characters
Here are the most common functions to check a character:
| Function | Returns true if the character is | Examples |
|---|---|---|
isalpha() |
a letter | 'a', 'Z' |
isdigit() |
a digit | '0', '7' |
isalnum() |
a letter or a digit | 'a', '7' |
isupper() |
an uppercase letter | 'A', 'Z' |
islower() |
a lowercase letter | 'a', 'z' |
isspace() |
white space, like a space, a tab or a new line | ' ', '\n' |
This example counts the letters and digits in a string. It loops through the string (see Strings and Loops) and checks each character:
Example
char text[] = "Room 42";
int letters = 0;
int digits = 0;
int i;
for (i = 0; i < strlen(text); i++) {
if (isalpha(text[i])) {
letters++;
} else if (isdigit(text[i])) {
digits++;
}
}
printf("Letters: %d\n", letters);
printf("Digits: %d\n", digits);
Try it Yourself »
The space in "Room 42" is not a letter or a digit, so it is not counted.
Change Characters
Use toupper() to change a letter to uppercase, and tolower() to change it to lowercase:
Example
printf("%c\n", toupper('a')); // A
printf("%c\n", tolower('B')); // b
printf("%c\n", toupper('7')); // 7
Try it Yourself »
Characters that are not letters, like '7', are not changed.
To change a whole string, change one character at a time in a loop:
Example
char text[] = "Hello World";
int i;
for (i = 0; i < strlen(text); i++) {
text[i] = toupper(text[i]);
}
printf("%s\n", text);
Try it Yourself »
Real-Life Example
Check if a password has at least one uppercase letter and one digit:
Example
char password[] = "Secret42";
int hasUpper = 0;
int hasDigit = 0;
int i;
for (i = 0; i < strlen(password); i++) {
if (isupper(password[i])) {
hasUpper = 1;
}
if (isdigit(password[i])) {
hasDigit = 1;
}
}
if (hasUpper && hasDigit) {
printf("The password is OK\n");
} else {
printf("The password needs an uppercase letter and a digit\n");
}
Try it Yourself »
Click "Try it Yourself", change the password to "secret", and see what happens.
Complete Character Reference
For a complete reference of character functions, go to our C <ctype.h> Library Reference.