Word Counter

Word Counter

Medium C Strings 35 views
Explanation Complexity

Problem Statement

Count how many words are in a sentence. Separate words with a space. Handle multiple spaces. Ignore leading/trailing spaces.

Input Format

A sentence (string) entered by the user.

Output Format

An integer representing total number of words.

Example

" this is a test "
4

Constraints

• Words are separated by spaces

• Multiple spaces may exist

• Leading and trailing spaces must be ignored

Concept Explanation

A word is counted when characters appear after a space or at the start, and spaces between words are handled properly.

Step-by-Step Explanation

1.Take the input sentence.

2.Initialize wordCount = 0.

3.Traverse the string character by character.

4.If current character is not a space and:

• it is the first character, or

• the previous character was a space
then a new word starts.

5.Increment wordCount when a new word starts.

6.Continue till the end of the string.

7.Print wordCount

Concept Explanation

A word is counted when characters appear after a space or at the start, and spaces between words are handled properly.

Step-by-Step Explanation

1.Take the input sentence.

2.Initialize wordCount = 0.

3.Traverse the string character by character.

4.If current character is not a space and:

• it is the first character, or

• the previous character was a space
then a new word starts.

5.Increment wordCount when a new word starts.

6.Continue till the end of the string.

7.Print wordCount

Input / Output Format

Input Format
A sentence (string) entered by the user.
Output Format
An integer representing total number of words.
Constraints
• Words are separated by spaces

• Multiple spaces may exist

• Leading and trailing spaces must be ignored

Examples

Input:
" this is a test "
Output:
4

Example Solution (Public)

C
#include <stdio.h>

int main() {
    char str[200];
    int i;
    int count = 0;

    printf("Enter a sentence: ");
    fgets(str, sizeof(str), stdin);

    for (i = 0; str[i] != '�'; i++) {

        // Word start condition
        if (str[i] != ' ' &&
           (i == 0 || str[i - 1] == ' ')) {
            count++;
        }
    }

    printf("Number of words = %dn", count);

    return 0;
}

Official Solution Code

#include <stdio.h>

int main() {
    char str[200];
    int i;
    int count = 0;

    printf("Enter a sentence: ");
    fgets(str, sizeof(str), stdin);

    for (i = 0; str[i] != '�'; i++) {

        // Word start condition
        if (str[i] != ' ' &&
           (i == 0 || str[i - 1] == ' ')) {
            count++;
        }
    }

    printf("Number of words = %dn", count);

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.