C has functions to test or manipulate individual characters.
The functions are all defined in the ctype.h header file.
To use the CTYPE functions, the ctype.h header file must be included in your source code:
#include <ctype.h>
CTYPE functions are of two categories: testing and manipulation.
The following table lists testing functions.
Function | Returns TRUE When ch is |
---|---|
isalnum(ch) | A letter of the alphabet (upper- or lowercase) or a number |
isalpha(ch) | An upper- or lowercase letter of the alphabet |
isascii(ch) | An ASCII value in the range of 0 through 127 |
isblank(ch) | A tab or space or another blank character |
iscntrl(ch) | A control code character, values 0 through 31 and 127 |
isdigit(ch) | A character 0 through 9 |
isgraph(ch) | Any printable character except for the space |
ishexnumber(ch) | Any hexadecimal digit, 0 through 9 or A through F (upper- or lowercase) |
islower(ch) | A lowercase letter of the alphabet, a to z |
isnumber(ch) | See isdigit() |
isprint(ch) | Any character that can be displayed, including the space |
ispunct(ch) | A punctuation symbol |
isspace(ch) | A white-space character, space, tab, form feed, or an Enter, for example |
isupper(ch) | An uppercase letter of the alphabet, A to Z |
isxdigit(ch) | See ishexnumber() |
manipulation functions.
toascii(ch) | The ASCII code value of ch, in the range of 0 through 127 |
---|---|
tolower(ch) | The lowercase of character ch |
toupper(ch) | The uppercase of character ch |
Generally speaking, testing functions begin with is, and conversion functions begin with to.
Every CTYPE function accepts an int value as the argument.
Every CTYPE function returns an int value.
#include <stdio.h> #include <ctype.h> int main() // w ww. j a v a 2s .c o m { char phrase[] = "this is a test."; int index,alpha,blank,punct; alpha = blank = punct = 0; /* gather data */ index = 0; while(phrase[index]) { if(isalpha(phrase[index])) alpha++; if(isblank(phrase[index])) blank++; if(ispunct(phrase[index])) punct++; index++; } /* print results */ printf("\"%s\"\n",phrase); puts("Statistics:"); printf("%d alphabetic characters\n",alpha); printf("%d blanks\n",blank); printf("%d punctuation symbols\n",punct); return(0); }