C Program to Count Words in a String

For our purpose, a word is a set of consecutive characters without any white-space. For example, ‘qnaplus‘ is a word but ‘qna plus‘ has two words. Here we’ll see how to write C program to count the number of words in a string.

We can think of a simple solution of counting the white spaces in the string. Number of white spaces is equal to the number of words. But it will not work if you have multiple white spaces in between two words or if you have only white spaces, no word at all.

We’ll figure out the algorithms that will work in all cases.

The Program

#include <stdio.h>

#define MAX_LEN 1024

int count_word(char *str) {
  int count = 0;
  int in_word = 0;
  int i = 0;
  do {
     if (str[i] == ' ' || str[i] == '\t' || str[i] == '\0') {
       if(in_word) {
         in_word = 0;
         count++;
       }
     } else {
       in_word = 1;
     }
  } while(str[i++]);

  return count;
}

int main() {
  char str[1024];
  printf("Enter a string: ");
  gets(str);

  printf("Number of words in the above string is %d.\n", count_word(str));
}

First we took input of a string and then passed the string to the count_word() function. The count_word() function returns the number of words in the input string.

The Logic

We traverse the whole string using a do-while loop. If we encounter a non-white-space character, we set the in_word flag to 1. But if we encounter a white-space character and the in_word flag is 1, we increment the word count. It suggests that a word ends with this white space. We set the in_word flag to 0 – we came out of the word.

When we encounter a white-space and the in_word flag is 0, we don’t increment the word count because it suggests that the previous character is also a white-space.

Note: Here we used do-while loop to process the last empty character (‘\0’) of the string.

Here is the output.

Another Logic

We can tweak the above logic little bit to get the same effect. When we’ll encounter a white-space, we can check whether the previous character is also a white-space or not. If the previous character is not a white-space, then we are just at the end of a word. So we increment the word count in this case. We don’t need in_word flag. Here is the modified word_count() function.

int count_word(char *str) {
  int count = 0;
  int i = 0;
  do {
     if (str[i] == ' ' || str[i] == '\t' || str[i] == '\0') {
       if((i > 0) && (str[i-1] != ' ' && str[i-1] != '\t' && str[i-1] != '\0')) {
         count++;
       }
     }
  } while(str[i++]);

  return count;
}

Using strtok()

We can implement our logic using strtok() function. The strtok() function can split a string into tokens specified by a delimiter. We can count the token split by white-space delimiter.

Here is our strtok() based implementation of word_count() function.

int count_word(char *str) {
  int count = 0;
  char* token = strtok(str, " ");
  while (token != NULL) {
    count++;
    token = strtok(NULL, " ");
  }

  return count;
}

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

2 thoughts on “C Program to Count Words in a String”

  1. Hi, love this tutorial and it’s very helpful. But I’d like to ask, how can you use the strtok function to count the numbers of words in a text file? I tried turning the file into an array (I used fopen and fcloes and fgets) and then using strtok on the array but that didn’t work unfortunately. Can you please explain to me how can I do it?


    1. #include /*stdio.h*/
      #include /*string.h*/
      #include /*stdlib.h*/

      #define MAX_LEN 1024

      int count_word(char *str) {
      int count = 0;
      char* token = strtok(str, " ");
      while (token != NULL) {
      count++;
      token = strtok(NULL, " ");
      }

      return count;
      }

      int main() {
      FILE *fp;
      char *line = NULL;
      size_t len = 0;
      int count = 0;

      fp = fopen("sample.txt", "r");
      if (fp == NULL) return -1;

      while (getline(&line, &len, fp) != -1) {
      count += count_word(line);
      }

      if (line) free(line);

      fclose(fp);

      printf("Number of words in the file is %d.\n", count);
      return 0;
      }

      The above program will read a file, ‘sample.txt’, from the current directory and return the number of words in it.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
5
0
0