Calculating Word Lengths from Text Input in C

Input Format: A single line of text ending with a period.

Output Format: The lengths of all words separated by spaces, with no trailing space.

Sample Input:

It's great to see you here.

Sample Output:

4 5 2 3 3 4

Approach 1: Using a Flag for First Output

This approach uses a flag to track whether the current word is the first one being printed. This allows proper formatting without a leading space on the first output.

#include <stdio.h>

int main(void)
{
    int charCount = 0;
    int isFirst = 1;
    char currentChar;

    while (scanf("%c", &currentChar) == 1)
    {
        if (currentChar == '.' || currentChar == '\n')
        {
            if (charCount > 0)
            {
                if (isFirst)
                {
                    printf("%d", charCount);
                    isFirst = 0;
                }
                else
                {
                    printf(" %d", charCount);
                }
            }
            if (currentChar == '.')
            {
                break;
            }
            charCount = 0;
        }
        else if (currentChar == ' ')
        {
            if (charCount > 0)
            {
                if (isFirst)
                {
                    printf("%d", charCount);
                    isFirst = 0;
                }
                else
                {
                    printf(" %d", charCount);
                }
                charCount = 0;
            }
        }
        else
        {
            charCount++;
        }
    }

    return 0;
}

Approach 2: Printing Space Before Each Word

This alternative method prints a space before each word length (except when no word has been output yet). The logic checks for the termination character first, then handles spaces, and finally increments the counter for non-space cahracters.

#include <stdio.h>

int main(void)
{
    int length = 0;
    char ch;
    int hasOutput = 0;

    while (1)
    {
        scanf("%c", &ch);

        if (ch == '.')
        {
            if (length > 0)
            {
                printf("%d", length);
            }
            break;
        }

        if (ch == ' ')
        {
            if (length > 0)
            {
                if (hasOutput)
                {
                    printf(" %d", length);
                }
                else
                {
                    printf("%d", length);
                    hasOutput = 1;
                }
                length = 0;
            }
        }
        else
        {
            length++;
        }
    }

    return 0;
}

Both approaches correctly handle consectuive spaces by only outputting a word length when transitioning from a non-space character to either a space or the terminating period.

Tags: c programming string processing input parsing Character Handling word counting

Posted on Sun, 12 Jul 2026 16:05:56 +0000 by r3drain