0
0
CProgramBeginner · 2 min read

C Program to Count Words in a String

You can count words in a string in C by scanning the string character by character and increasing a count each time you find a transition from a space to a non-space character, for example: if ((str[i] != ' ' && str[i] != '\t' && str[i] != '\n') && (i == 0 || str[i-1] == ' ' || str[i-1] == '\t' || str[i-1] == '\n')) count++;.
📋

Examples

InputHello world
Output2
Input This is a test string
Output5
Input
Output0
🧠

How to Think About It

To count words, think of words as groups of characters separated by spaces or tabs. We scan the string from start to end, and every time we find a character that is not a space and is either at the start or right after a space, we count it as a new word.
📐

Algorithm

1
Get the input string.
2
Initialize a word count to zero.
3
Loop through each character in the string.
4
If the current character is not a space and either it is the first character or the previous character is a space, increase the word count.
5
After the loop ends, return or print the word count.
💻

Code

c
#include <stdio.h>
#include <string.h>

int main() {
    char str[1000];
    int count = 0;
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    for (int i = 0; str[i] != '\0'; i++) {
        if ((str[i] != ' ' && str[i] != '\t' && str[i] != '\n') &&
            (i == 0 || str[i-1] == ' ' || str[i-1] == '\t' || str[i-1] == '\n')) {
            count++;
        }
    }

    printf("Number of words: %d\n", count);
    return 0;
}
Output
Enter a string: Hello world Number of words: 2
🔍

Dry Run

Let's trace the input "Hello world" through the code

1

Start scanning string

str = "Hello world\n"; count = 0; i = 0

2

Check first character 'H'

'H' is not space and i=0, so count = 1

3

Scan characters until space

Characters 'e', 'l', 'l', 'o' are not spaces but previous chars are not spaces, so count stays 1

4

At space character

str[5] = ' ' (space), no count increase

5

Next character 'w'

'w' is not space and previous char is space, count = 2

6

Continue scanning rest

Characters 'o', 'r', 'l', 'd' no count increase

7

End of string

Total count = 2

IndexCharacterPrevious CharacterCount
0HN/A1
1eH1
2le1
3ll1
4ol1
5 o1
6w 2
7ow2
8ro2
9lr2
10dl2
11\nd2
💡

Why This Works

Step 1: Identify word start

A word starts when a non-space character follows a space or is at the string start, so we check these conditions to count words.

Step 2: Ignore multiple spaces

By only counting when previous character is space, we avoid counting spaces or multiple spaces as words.

Step 3: Use loop to scan string

Looping through each character lets us check every position for word starts efficiently.

🔄

Alternative Approaches

Using strtok function
c
#include <stdio.h>
#include <string.h>

int main() {
    char str[1000];
    int count = 0;
    char *token;
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    token = strtok(str, " \t\n");
    while (token != NULL) {
        count++;
        token = strtok(NULL, " \t\n");
    }

    printf("Number of words: %d\n", count);
    return 0;
}
This method uses built-in tokenization but modifies the original string.
Counting transitions with a flag
c
#include <stdio.h>

int main() {
    char str[1000];
    int count = 0, inWord = 0;
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] != ' ' && str[i] != '\t' && str[i] != '\n') {
            if (!inWord) {
                count++;
                inWord = 1;
            }
        } else {
            inWord = 0;
        }
    }

    printf("Number of words: %d\n", count);
    return 0;
}
This method uses a flag to track if inside a word, which can be clearer and efficient.

Complexity: O(n) time, O(1) space

Time Complexity

The program scans the string once, so time grows linearly with string length.

Space Complexity

Only a few variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

The direct scan with conditions is fastest and simplest; strtok is convenient but modifies input.

ApproachTimeSpaceBest For
Direct scan with conditionsO(n)O(1)Simple and fast word counting
strtok tokenizationO(n)O(1)When modifying input is acceptable
Flag tracking methodO(n)O(1)Clear logic for word boundaries
💡
Use a flag to track when you enter and leave words for simpler counting logic.
⚠️
Counting spaces instead of word starts causes wrong counts when multiple spaces appear.