Nearby lessons
68 of 124C - String Characters
Working with the individual characters of a string — indexing, modifying, and classifying them with the <ctype.h> functions isalpha, isdigit, toupper, tolower and friends.
Characters Are Just Small Integers
Every char holds a number — its ASCII code. That is why comparisons, arithmetic, and array indexing all work on characters:
Reading and Writing by Index
Index a string exactly like any array. Both reads and writes are allowed on a char array:
The ctype.h Classification Functions
These return non-zero (true) when the character belongs to the category. Include <ctype.h> to use them:
| Function | True when the character is | Example match |
|---|---|---|
isalpha(c) | A letter | a–z, A–Z |
isdigit(c) | A digit | 0–9 |
isalnum(c) | A letter or digit | a–z, A–Z, 0–9 |
isspace(c) | Whitespace | space, \t, \n |
isupper(c) | Uppercase | A–Z |
islower(c) | Lowercase | a–z |
ispunct(c) | Punctuation | ! , . ? |
Counting Character Categories
One pass through the string, one counter per category — the standard text-analysis pattern:
Case Conversion
toupper and tolower return the converted character. They do not change anything in place, so you must assign the result back:
Converting In Place
To change the original string, assign the result back into the same slot:
Counting Vowels and Consonants
Normalise the case first, then a single comparison covers both cases:
Digit Characters to Numbers
Because digits sit consecutively in ASCII, subtracting '0' converts a digit character to its value:
Title Case — A Practical Combination
Capitalise the first letter of each word by tracking whether the previous character was a space:
Common Mistakes
- Discarding the return value —
toupper(s[i]);does nothing on its own. Writes[i] = toupper(s[i]);. - Forgetting
<ctype.h>— the code may still compile with warnings and behave oddly. - Comparing to a string —
s[i] == "a"compares a character to an address. Use'a'. - Overwriting the terminator — building a new string and forgetting the final
'\0'. - Assuming letters are contiguous —
'a'to'z'is contiguous in ASCII, but comparingc >= 'a' && c <= 'z'is less portable thanislower(c).
ctype.h functions take an int and are defined for values representable as unsigned char plus EOF. With a plain char that happens to be signed, a byte above 127 becomes negative and the behaviour is undefined. In production code, cast: isalpha((unsigned char) s[i]).- s[i] reads or writes the character at position i.
- Include <ctype.h> for the is... and to... functions.
- isalpha, isdigit, isspace, isupper, islower classify characters.
- toupper and tolower return the converted character — they do not modify in place.
- Characters are small integers, so arithmetic like s[i] - '0' works.