🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Count Words in C
Why spaces plus one fails, and how a two-state scan counts words correctly and safely.
How would you count words in a string in C? Most beginners say: count the spaces and add one. That answer is wrong more often than it is right, and finding out why is the point of this lecture of our free C programming course. We will replace the shaky idea with a tiny state machine, read a line of text safely with fgets, add a longest-word statistic, and discuss where tokenising shows up in embedded C programming, for example in serial console and AT command parsers. All code is original and tested.
What You Will Learn
- Why counting spaces fails on real text
- How to count words in a string in C with an in-word flag
- Which characters count as white space and how isspace helps
- How to read one line with fgets and detect that it was cut short
- Why the old gets function is gone from the language
- How to compute the word count and the longest word in a single pass
Prerequisites
You should understand char arrays, the null terminator, pointer walking through a string, and how if and else if chains work. The ctype.h header and strcspn were introduced in the earlier lectures of this free C tutorial.
Why Counting Spaces Fails
The “spaces plus one” rule assumes exactly one space between words, no leading or trailing spaces, and a non-empty line. Real input breaks all three assumptions. Here is a side-by-side comparison of the naive rule and a correct counter on five realistic strings.
#include <ctype.h>
#include <stdio.h>
static int count_naive(const char *s)
{
int spaces = 0;
for (; *s != '\0'; s++)
if (*s == ' ')
spaces++;
return spaces + 1;
}
static int count_words(const char *s)
{
int words = 0;
int in_word = 0;
for (; *s != '\0'; s++) {
if (isspace((unsigned char)*s)) {
in_word = 0;
} else if (!in_word) {
in_word = 1;
words++;
}
}
return words;
}
int main(void)
{
struct { const char *label; const char *text; } tests[] = {
{ "plain", "embedded c course" },
{ "double spaces", "free c tutorial" },
{ "edge spaces", " leading and trailing " },
{ "empty string", "" },
{ "tab between", "tab\tsplit" }
};
const int count = (int)(sizeof tests / sizeof tests[0]);
printf("%-15s %-6s %s\n", "case", "naive", "robust");
for (int i = 0; i < count; i++)
printf("%-15s %-6d %d\n", tests[i].label,
count_naive(tests[i].text), count_words(tests[i].text));
return 0;
}
Build and run:
gcc -std=c17 -Wall -Wextra -o word_count word_count.c
./word_count
case naive robust
plain 3 3
double spaces 7 3
edge spaces 7 3
empty string 1 0
tab between 1 2
The naive column is only right for the first case. Doubled spaces inflated the answer from 3 to 7, leading and trailing spaces did the same, the empty string produced 1 instead of 0, and a tab between words was not seen at all. If this counter drove a command parser, it would think a blank line is a command.
| Assumption of “spaces plus one” | Real-world violation |
|---|---|
| Exactly one space between words | Users type extra spaces or align columns |
| No space at either end | Copy and paste adds invisible spaces |
| Space is the only separator | Tabs and newlines also separate words |
| At least one word exists | Blank lines are common |
How to Count Words in a String in C Correctly
A word starts at the moment you move from white space (or the beginning of the string) onto a non-space character. So instead of counting separators, count those transitions. You only need one flag that remembers whether the previous character was part of a word.
In the function count_words from the program above, the logic is exactly the diagram. When isspace reports white space, the flag drops to zero. When the character is not white space and the flag is zero, a new word has begun: set the flag and add one. A character inside a word changes nothing.
isspace recognises the space, horizontal tab, newline, vertical tab, form feed and carriage return. As with every ctype function, cast the character to unsigned char before passing it in. The function never reads past the terminator, uses no memory beyond two integers, and visits each character once, so it is O(n) time and O(1) space.
Read a Line to Count Words in a String in C
Counting from literals is fine for testing, but real programs read text. Older books use gets for this. Do not. gets cannot know how big your buffer is, so any long line overflows it, and for that reason it was removed from the language in C11. The safe replacement is fgets, which takes the buffer size.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
static int count_words(const char *s)
{
int words = 0;
int in_word = 0;
for (; *s != '\0'; s++) {
if (isspace((unsigned char)*s)) {
in_word = 0;
} else if (!in_word) {
in_word = 1;
words++;
}
}
return words;
}
int main(void)
{
char line[64];
printf("Enter a line of text: ");
if (fgets(line, sizeof line, stdin) == NULL) {
puts("no input");
return 1;
}
size_t len = strcspn(line, "\n");
int cut = (line[len] != '\n') && (len == sizeof line - 1);
line[len] = '\0';
printf("words = %d\n", count_words(line));
if (cut)
printf("warning: line was longer than %zu characters, the rest was ignored\n",
sizeof line - 1);
return 0;
}
fgets stores the newline if it fits, so the code uses strcspn to find it and remove it. The two lines below that matter are worth reading slowly:
size_t len = strcspn(line, "\n");
int cut = (line[len] != '\n') && (len == sizeof line - 1);
If a newline was found, the line fitted. If there is no newline and the buffer is completely full, the input was longer than the buffer and fgets cut it off. A last line without a newline that still fits, which happens at the end of a file or with piped data, is correctly not reported as cut.
Try it with a normal line and then with a very long one:
printf 'free embedded c course\n' | ./fgets_count
python3 -c "print('ab ' * 40)" | ./fgets_count
Enter a line of text: words = 4
Enter a line of text: words = 21
warning: line was longer than 63 characters, the rest was ignored
The long line holds 120 characters but the buffer keeps only 63, which is why the answer is 21 words and the warning appears. When you pipe input there is no echoed keystroke, so the result continues on the prompt line. In a terminal it looks normal.
Word Count and Longest Word in One Pass
Once you see the counter as a scan over characters, adding more statistics costs almost nothing. This version tracks the length of the current word and remembers the longest, and it uses a small trick: the loop runs for (;; s++) and treats the null terminator as one more separator. That means the final word is closed off naturally, with no special-case code after the loop.
#include <ctype.h>
#include <stdio.h>
static void word_stats(const char *s, int *words, int *longest)
{
int current = 0;
*words = 0;
*longest = 0;
for (;; s++) {
if (*s != '\0' && !isspace((unsigned char)*s)) {
if (current == 0)
(*words)++; /* first letter of a new word */
current++;
if (current > *longest)
*longest = current;
} else {
current = 0;
if (*s == '\0')
break;
}
}
}
int main(void)
{
const char *texts[] = {
"firmware updates need careful bootloader design",
" uart spi i2c ",
""
};
const int count = (int)(sizeof texts / sizeof texts[0]);
for (int i = 0; i < count; i++) {
int w, l;
word_stats(texts[i], &w, &l);
printf("words=%d longest=%d <- \"%s\"\n", w, l, texts[i]);
}
return 0;
}
words=6 longest=10 <- "firmware updates need careful bootloader design"
words=3 longest=4 <- " uart spi i2c "
words=0 longest=0 <- ""
Three outputs show the variety. The first sentence has six words and the longest, bootloader, has ten letters. The second has three words despite the extra spaces. The empty string gives zero and zero.
Real-World Uses in Embedded Systems
- Command consoles. Knowing the number of words tells you how many arguments a typed command has before you try to parse them.
- AT commands and modem replies. Space- or comma-separated fields need counting before extraction.
- Log analysis tools. Host-side utilities that check whether each log line has the expected number of fields.
- Display layout. Word wrapping on a small LCD needs the length of the longest word to choose a font size.
If you need the words themselves rather than their count, look at strtok or strtok_r. They split a string in place by writing null bytes over the separators, which means the original text is destroyed and the string must be writable. Counting first with the method above lets you size an array of pointers before splitting.
Common Mistakes When You Count Words in a String in C
| Mistake | Result | Fix |
|---|---|---|
| Counting spaces and adding one | Wrong on doubled, leading, trailing or no spaces | Count transitions into a word |
| Comparing only with the space character | Tabs and newlines are missed | Use isspace |
| Using gets | Unfixable buffer overflow, removed from C11 | Use fgets with sizeof |
| Leaving the newline in the buffer | An extra invisible character at the end | Strip it with strcspn |
| Not noticing truncated input | Silently wrong count for long lines | Detect and report the cut |
| Passing char directly to isspace | Undefined behaviour for negative values | Cast to unsigned char |
Best Practices, Performance and Security
- When you count words in a string in C, keep the counter as its own function that accepts a const char *. You can then test it on literals and reuse it on any buffer.
- Define what a word is for your application. Words separated by punctuation, hyphens or apostrophes need a different character test than white space.
- Always bound the input. A fixed buffer plus fgets protects you from overlong lines sent over a UART or a network socket.
- Report truncation instead of pretending it did not happen.
- The single-pass method does no allocation, which suits systems without a heap.
- Test with the empty string, only spaces, one word, tabs, and leading and trailing white space.
Summary and Key Takeaways
- To count words in a string in C, do not use spaces plus one. Count transitions from separator to word instead.
- An in-word flag and isspace make a correct, single-pass counter.
- Use fgets, never gets, and detect truncation by checking for a missing newline on a full buffer.
- Treating the null terminator as a separator removes special cases at the end of the string.
- The same scan can gather extra facts such as the longest word.
Conclusion
To count words in a string in C reliably, think in transitions, not separators. That one change handles empty lines, extra spaces and tabs, and it extends easily to richer statistics. Together with safe line input it gives you a small, allocation-free tool that fits comfortably on a microcontroller. The next lecture of our free embedded C course finishes this strings chapter: we remove the characters two strings have in common, and we close with a quiz and interview questions covering the whole set of string-processing lectures.
Frequently Asked Questions About Counting Words in C
How do I count words in a string in C?
Walk through the string with a flag that records whether you are inside a word. Each time you move from white space onto a non-space character, add one to the count.
Why is counting spaces plus one not reliable?
It breaks on repeated spaces, leading or trailing spaces, tabs, and empty strings.
Why was gets removed from C?
gets cannot limit how many characters it stores, so it can always overflow the buffer. It was removed in C11. Use fgets instead.
What characters does isspace treat as white space?
Space, tab, newline, vertical tab, form feed and carriage return in the default locale.
How can I tell that fgets truncated my line?
If the buffer contains no newline and is completely full, the line was longer than the buffer.
Is strtok a good way to count words?
It works but modifies the string by overwriting separators and is not reentrant. A read-only counting loop is safer when you only need the number.
Does this method work for non-English text?
It works on single-byte text split by white space. UTF-8 text and languages without spaces between words need different handling.
Learn C Programming for Embedded Systems
Clean text handling is the base of every serial console. Continue the free C programming course and finish the strings chapter.

2 Comments