C program to count number of words in a string

Category: C Program
Tags: #cprogram#string

Learn how to count the total number of words in a string using C without pointers or separate functions. This step-by-step guide includes a sample program and detailed explanation.

Counting the number of words in a string is a common task in text processing. In this article, we'll walk through a C program that accomplishes this task using basic string manipulation techniques, without using pointers or separate functions.

Introduction

A word is typically defined as a sequence of characters separated by whitespace (spaces, tabs, or newline characters). We'll write a C program to count the number of words in a given string, considering these delimiters.

Algorithm

  1. Initialize Variables:
    • count to store the number of words.
    • inWord to track if we are inside a word.
  2. Traverse the String:
    • Use a loop to go through each character of the string.
    • Check for whitespace characters to determine the boundaries of words.
  3. Counting Words:
    • If a non-whitespace character is found and we are not already in a word, increment the word count and set inWord to true.
    • If a whitespace character is found, set inWord to false.
  4. Edge Cases:
    • Handle empty strings and strings with leading/trailing/multiple spaces.

Write a C program to count number of words in a string

#include <stdio.h>

int main() {
    char str[1000];
    int count = 0;
    int inWord = 0;

    // Input string from user
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Traverse the string using array indexing
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n') {
            inWord = 0;
        } else if (!inWord) {
            inWord = 1;
            count++;
        }
    }

    // Print the result
    printf("Total number of words: %d\n", count);

    return 0;
}

Output

Enter a string: Learn programming at ProCoding
Total number of words: 4

Explanation

  1. Include Headers:
    • We include the standard input-output header (stdio.h) for input and output functions.
  2. Main Function:
    • We declare a character array str to hold the input string.
    • We initialize count to 0 and inWord to 0.
    • Using fgets, we read the input string from the user.
    • The for loop traverses each character in the string using array indexing.
    • If the character is a white space, inWord is set to 0.
    • If the character is not white space and inWord is 0, it indicates the start of a new word. We increment the word count and set inWord to 1.
  3. Counting Logic:
    • The for loop iterates through each character of the string until the null terminator ('\0') is encountered.
    • Within the loop, we check if the current character is a whitespace (' ', '\t', or '\n').
    • If it is, we set inWord to false, indicating that we are not currently inside a word.
    • If it is not white space and inWord is 0, it means we have encountered the start of a new word. We increment the word count and set inWord to 1.
  4. Edge Cases:
    • The program correctly handles empty strings, multiple spaces between words, and leading/trailing spaces.

Recommended Posts