Program to Count Number of Words in String in C (4 -Methods)

Program-to-Count-Number-of-Words-in-String-in-C-language

Program Description:

Write a Program to count number of words in string in c programming language. The program should accept a string from the user and count the total number of words in the given string.

We are going to look at a few methods to count a number of words in a string and Each program will be followed by a detailed step-by-step explanation with program output. We also provided instructions for compiling and running the program using your compiler.

📢 This Program is part of the C String Practice Programs series

Before looking at the programs, Let’s understand the excepted input and output of the program.

Example Input and Output:

Input:

Enter a string : Learn C Programming Online at SillyCodes.com

Output:

Number of words in the string is : 6

The input string contains six words.

Prerequisites:

Please go through the following Strings, Functions, and Arrays tutorials to better understand the program.

We are going to look at Four Methods to count the number of words in a string

  1. Basic Method: Iterative method to count the number of words in a string. This program might fail if your string contains extra spaces.
  2. Improved Method: Calculates the word count. This program can handle extra spaces in the string.
  3. User-Defined Function: This is a modified version of Method-2, Which uses the C functions to count words in a string.
  4. Using strtok function: Counts the number of words in a string using the strtok string library function.

Let’s look at all these methods one by one.

Basic Method: Count Number of Words in String in C Program:

This is a basic form of calculating the words in a string. This method traverses through the input string and looks for the spaces. This method will fail if your string contains extra spaces. please look at the Improved method if you are string contains extra spaces.

Let’s look at the step by step instructions of the program.

Algorithm to count number of words in string basic method:

  1. Start the program by declaring the input string and let’s say it as str.
  2. Take the input string from the user and update the str string. we are using gets() function to read the string.
  3. Initialize a variable called nWords with Zero(0). This nWords contain the total number of words in the string.
  4. To count the number of words in a string, Iterate over the string and Increment the nWords whenever a space character occurs.
  5. Start the For Loop by initializing i to Zero(0). It will continue looping as long as the current character ( str[i]) is not a null character ( '\0'). At each iteration, i is incremented by 1.
    • For each iteration, Check if the str[i] is equal to space ( ' '). Use if(str[i] == ' '). We can check for tabs and newlines depending on our requirements or we can simply use the isspace() function from ctype.h header file.
    • If the above condition is true, Then increment the nWords variable by 1. – i.e nWords++;
  6. Once the above loop is completed, Check if the i value is greater than Zero(0), If so increment the nWords by 1. ( Because we need to increment for the first word).
  7. Finally, Display the result on the console using printf() function.

📢 This method will fail, If your input string contains extra spaces ( Leading, Trailing, or in between words)

Basic Method: Count the Number of words in a string in C Program:

Here is the program to count words in c.

Program Output:

Compile and Run the above program.

Test Case 1:

count-number-of-words-in-string-using-loops-program-output-

As we can see from the above output, The program is properly calculating the words in a string if the input string doesn’t have any extra spaces.

Test Case 2: String with extra spaces:

As the input string has extra spaces, The program generated incorrect results. To overcome this problem we need to use the following improved method.

Improved Method: Count Number of Words in String with extra spaces in C:

In this method, The program will count the number of words in a string, Even though the string has extra spaces.

We should be able to count the number of words for

Let’s look at the program Algorithm/Explanation.

Count Number of words in a string with extra spaces Program Algorithm:

  1. As usual, Take the input string from the user and update the str string. Also initialize the nWords variable with Zero(0).
  2. To calculate the number of words in string, Traverse through the string character by character and increment the nWords only if the str[i] is not equal to space( ' ') and str[i+1] is equal to space( ' ') or NULL character.
  3. Start the for loop from i = 0 and go till we reach the end of the string. i.e for(i = 0; str[i]; i++)
    • At Each Iteration, Check the if( str[i] != ‘ ‘ && (str[i+1] == ‘ ‘ || str[i+1] == ‘\0’) ) condition. If this condition is true, Then increment the nWords – i.e nWords++;
    • Otherwise, Continue to the next iteration.
  4. Once the above Step 3 is completed, The nWords will have the total number of words in the input string.
  5. Display the nWords on the console.

Program to count words in string with extra spaces:

Let’s convert above algorithm into the C program.

Program Output:

Compile the program using GCC(Any compiler)

$ gcc count-words-adv.c

Run the program.

Test Case 1: Normal String

The input string Programming is Fun contains three words.

Test Case 2: String with Extra Spaces:

count-number-of-words-in-a-string-with-extra-spaces-in-c-language

In this case, The input string Lot      of      extra       spaces        between       words has many extra spaces in between the words. Still, the program is able to calculate the number of words in the string properly and returned the result as 6.

Test Case 3: String with Leading Spaces:

In this method, The input string has the leading spaces, The program properly counted the number of words and returned the result.

Test Case 4: String with Trailing Spaces:

The input string trailing      spaces    string has spaces in between the words and also the trailing spaces. The program counted the number words and returned the result as the 3.

As we can see from the above test cases, The program is providing the desired results.

User-defined Function: Program to Count Number of words in a string using functions in C Language:

Let’s move the above word counting logic from the main() function to a separate function. So that we can reuse the code.

By using the functions we can define a function once and can call it as many times as we want. Functions also increase the readability of the program and make it easier to debug issues. Here are the benefits using the functions in programming.

Here is the modified program, Where we defined a function called countWords to count the number of words in a string.

This function takes a string as the input and counts the total number of words in the string and returns the result back to the caller.

The prototype of the countWords function

int countWords(char * str)

Program Output:

Let’s compile and run the program and observe the output.

count-words-in-sentence-using-functions-in-c

As we can see from the above input and outputs, The program is giving the desired results.

strtok library function: Count Number of Words in a String in C using strtok function:

We can also use the strtok() library function to count the number of words in a string. This method demonstrates the same.

The syntax of strtok function is

char * strtok(char * str, const char * delimiter)

The strtok() function parses the input string str into the sequence of tokens based on the delimiter.

The first call to strtok() function should be input string str and delimiter. But for the subsequent calls to strtok() that parses the same string the string( str) should be NULL.

Now, We know how strtok() function is used to split the string into the tokens. Let’s use this strtok() function to count the number of words in the string.

Call the strtok() function with input string and delimiter space( " "). Note this space is a string, not a character.

The strtok() function returns a character pointer. store it in ptr. Then use a while loop to make subsequent calls to strtok() function and increment the wordCnt variable.

The wordCntvariable will be initialized with zero and will be incremented by 1 at each iteration of the above while loop.

Here is the program to count number of words in a string using the strtok() function in c programming language.

Program Output:

Compile and Run the program.

count-number-of-words-in-string-using-strtok-function-in-c

As we can see from the above output, The input string Who built pyramids? contains three words and strtok() function is able to properly count the number of words in the string.

Related String Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

2 Responses

  1. […] C Program to Count Number of Words in a String […]

  2. […] C Program to Count Number of Words in a String […]

Leave a Reply