🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C String Counting Programs
Count consonants, spaces, characters and whole words in C strings with clean, reusable functions.
What You Will Learn
- How to walk a C string with a pointer and stop at the terminator
- How to classify letters into vowels, consonants and spaces
- How to write a reusable count_char function with correct types
- How to count whole words with strstr plus boundary checks
- Why fgets, unsigned char casts and size_t matter for embedded C programming
Prerequisites
- The previous Strings lectures: string literals, char arrays and the terminator
- Basic loops, if/switch and functions
- A C compiler such as gcc or an embedded toolchain
Every serious program that touches text has to count something: how many vowels are in a command, how many times a delimiter appears in a log line, how often a keyword shows up in a configuration file. In this lecture of our free C programming course you will learn how to count characters in a C string the way working engineers do it. This is core embedded C programming skill, because firmware spends a surprising amount of time scanning short text buffers that arrive over UART, SPI flash or a Bluetooth link.
We continue from the string exercises at the end of the Strings chapter. Instead of solving them one by one, we group them by the technique they train, and each lecture in this batch gives you a small, reusable routine. Here we cover three of them: classifying characters (consonants, vowels, spaces), counting one chosen character, and counting whole-word occurrences. Every program was compiled with -std=c11 -Wall -Wextra -pedantic and the output shown is real.
Why Counting Characters Matters in Embedded C Programming
On a microcontroller you rarely have a heap, a regex library or a spare kilobyte of stack. So you count by hand, in one pass, with a pointer. Some everyday jobs that reduce to counting:
- Checking that an AT command reply contains exactly the number of commas the modem manual promises before you trust the fields.
- Measuring how many padding spaces a display line needs for centring text on a small OLED.
- Counting how many times a log tag appears in a ring buffer to decide whether a fault is repeating.
- Validating user-typed Wi-Fi names or Bluetooth device names against a length and character policy.
The three programs below use only the standard library headers stdio.h, string.h and ctype.h, so they run unchanged on a PC for practice and on a bare-metal target with a C library.
How to Count Characters in a C String: The Traversal Model
A C string is an array of char that ends with the byte 0. There is no stored length. To visit every character you start a pointer at the first byte and walk until you see the terminator. Counting is just visiting plus an if.
The terminator is never counted. That is why the loop condition is *p != '\0' and not a length you computed earlier. If you do call strlen first, remember that it walks the whole string once by itself, so using it in the loop condition of a for would make your program walk the string again for every character.
Classify Consonants, Vowels and Spaces
The first exercise asks for consonants and spaces. A consonant is a letter that is not a vowel, so we need two tests: is it a letter at all, and which letter is it. The isalpha function answers the first, and a switch over the lowercase form answers the second. Digits and punctuation go into an others bucket so nothing is silently lost.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char line[128];
unsigned vowels = 0, consonants = 0, spaces = 0, others = 0;
printf("Enter a line: ");
if (fgets(line, sizeof line, stdin) == NULL)
return 1;
for (const char *p = line; *p != '\0'; p++) {
unsigned char c = (unsigned char)*p;
if (c == '\n')
continue; /* fgets keeps the newline */
if (isalpha(c)) {
switch (tolower(c)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
vowels++;
break;
default:
consonants++;
}
} else if (c == ' ') {
spaces++;
} else {
others++;
}
}
printf("vowels=%u consonants=%u spaces=%u others=%u\n",
vowels, consonants, spaces, others);
return 0;
}
Build and run it like this:
gcc -std=c11 -Wall -Wextra -pedantic -o count_classes count_classes.c
./count_classes
Enter a line: Embedded C is fun 24x7
vowels=5 consonants=10 spaces=4 others=3
Check the answer by hand. The vowels are the two e characters and the capital E in Embedded, the i in is and the u in fun: five. The consonants are m, b, d, d, d, C, s, f, n and x: ten. The four spaces separate five words. The characters 2, 4 and 7 land in others: three. Always verify a counting program against a hand-counted sample before you trust it on real input.
Two details that bite beginners. fgets keeps the newline at the end of the buffer, so we skip '\n' explicitly. And every ctype.h function expects a value that fits in unsigned char (or EOF). Passing a plain char that happens to be negative is undefined behaviour, which is why the code casts first.
Count One Character with a Function
The next exercise asks for a function that takes a string and a character and returns how many times the character occurs. The design questions are small but worth discussing, because they show up in every code review.
| Design choice | Our pick | Reason |
|---|---|---|
| String parameter type | const char * | The function only reads the string, so const lets callers pass literals and read-only buffers without warnings. |
| Return type | size_t | A count can never be negative and can in principle be as large as the buffer, which is what size_t models. |
| Argument order | string first, character second | Matches strchr and the exercise statement, so the call reads naturally. |
| Empty string | returns 0 | The loop body never runs; no special case is needed. |
The complete function appears in the program below, together with the third routine of this lecture. Read count_char first: it is a plain loop that increments n on a match.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static size_t count_char(const char *s, char ch)
{
size_t n = 0;
for (; *s != '\0'; s++)
if (*s == ch)
n++;
return n;
}
static int is_word_char(unsigned char c)
{
return isalnum(c) || c == '_';
}
/* Counts whole-word matches only. */
static size_t count_word(const char *text, const char *word)
{
size_t wlen = strlen(word), n = 0;
if (wlen == 0)
return 0;
for (const char *p = text; (p = strstr(p, word)) != NULL; p += wlen) {
int left_ok = (p == text) || !is_word_char((unsigned char)p[-1]);
int right_ok = !is_word_char((unsigned char)p[wlen]);
if (left_ok && right_ok)
n++;
}
return n;
}
int main(void)
{
const char *log = "the cat saw the other cat near the hat";
size_t raw = 0;
for (const char *p = log; (p = strstr(p, "the")) != NULL; p += 3)
raw++;
printf("text : %s\n", log);
printf("count 't' : %zu\n", count_char(log, 't'));
printf("raw \"the\" : %zu (strstr only)\n", raw);
printf("word \"the\" : %zu (whole words)\n", count_word(log, "the"));
printf("word \"cat\" : %zu\n", count_word(log, "cat"));
return 0;
}
Count Whole Words, Not Substrings
The standard function strstr finds the first occurrence of one string inside another, which makes a word counter look trivial: call it in a loop and count the hits. The trap is that strstr knows nothing about word boundaries. Searching for the inside the word other produces a hit, because o-the-r contains those three letters, yet other is not the word the. A naive counter reports a hit that is not a word at all.
The fix is a boundary test on both sides of every hit. A hit is a real word only if the character before it (if any) and the character after it are not word characters. We define a word character as a letter, a digit or an underscore, which matches how identifiers behave in C source code. Compile and run:
gcc -std=c11 -Wall -Wextra -pedantic -o count_search count_search.c
./count_search
text : the cat saw the other cat near the hat
count 't' : 7
raw "the" : 4 (strstr only)
word "the" : 3 (whole words)
word "cat" : 2
The raw count of 4 includes the false hit inside other; the whole-word count of 3 is the correct answer. The letter t appears seven times in the sentence, including the ones inside the, other and hat.
Advancing by wlen means overlapping matches are not counted: searching for aa in aaaa reports 2, not 3. If your application needs overlapping counts, advance by one instead. State which behaviour you chose in a comment, because the next reader will wonder.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Count is one too high on typed input | The newline from fgets was counted as a character | Skip '\n' or strip it with strcspn before counting |
| Strange results with accented or high-bit text | Plain char is signed and was passed to isalpha | Cast to unsigned char before every ctype call |
| Program hangs or crashes while counting | The buffer was never terminated | Initialise arrays and always terminate strings you build by hand |
| Word count includes parts of longer words | Only strstr was used | Add the left and right boundary test |
| Count of an empty word is huge or loops forever | strstr(p, "") matches everywhere and wlen is 0 | Return 0 early when the word is empty |
Best Practices, Performance and Security
- Complexity: classification and character counting are O(n), one pass.
count_wordis O(n times m) in the worst case; fine for log lines, but use a smarter search for megabyte buffers. - One pass, many counters: when you need several statistics, update all of them in the same loop instead of scanning the string once per statistic. Cache friendliness matters even on small cores.
- Never use
gets: it cannot be told how large the buffer is and was removed from the C standard. Usefgetswithsizeofof the buffer. - Treat input as hostile: text from a network or radio link may lack a terminator. When a length is known, use bounded forms such as
strnlenor loop over the known length. - Name your counters by meaning, not by letter:
consonantsexplains itself,c2does not.
Practice Challenges
- Extend
count_classes.cso it also reports uppercase and lowercase letters separately. - Write
count_digitsthat returns how many decimal digits a string contains, then use it to reject a Wi-Fi password made only of digits. - Change
count_wordto treat a hyphen as a word character, then explain how the result for cat-nap changes.
Key Takeaways
- A C string is walked with a pointer until the terminator; the terminator itself is never counted.
- Classification needs two questions: is it a letter, and which letter.
count_charis a plain loop; takeconst char *and returnsize_t.strstralone counts substrings; add boundary checks to count whole words.- Cast to
unsigned charfor ctype calls and usefgets, nevergets.
Conclusion
Counting is the simplest string job and also the best place to learn the habits that keep embedded code safe: a clear loop condition, a correct type, a verified sample and an honest definition of what you are counting. Once you can count characters and words reliably, replacing and deleting them, which we do in the next lecture, is only a small step further.
If you are following this free C tutorial in order, run all three programs, change the sample text and predict the output before you press Enter. That habit is worth more than reading ten more pages. Continue with the next lecture of this free embedded C course to learn in-place editing of strings.
Frequently Asked Questions
How do I count characters in a C string?
Walk a pointer from the first byte until you reach the '\0' terminator and update a counter whenever the current character passes your test. For the total length, strlen does exactly that.
Why does my counter include the newline when I use fgets?
fgets stores the newline that ended the line. Skip it in the loop, or remove it first with line[strcspn(line, "\n")] = '\0'.
What is the difference between counting a substring and counting a word?
strstr finds any occurrence of the letters, even inside a longer word. A word count must also check that the characters on both sides are not letters, digits or underscores.
Why cast to unsigned char before calling isalpha?
The ctype functions accept values representable as unsigned char or EOF. A negative char value is undefined behaviour, so the cast keeps portable code safe.
Should the counter be int or size_t?
Use size_t when the count is bounded by the string length, because it matches strlen and indexes. Use a plain unsigned type for small classification counters.
Is this lecture part of a free embedded C course?
Yes. EmbeddedPathashala offers a free C programming course focused on embedded systems, and these string routines are the same ones used in firmware command parsers.
Keep Going With the Free Embedded C Course
EmbeddedPathashala teaches embedded C programming, Linux kernel development and device drivers for free. Pick the next lecture and keep your streak going.

2 Comments