Program to Count Number of Words in a Given String and File

count number of words

We can easily count number of words in a given string or file to search the space between the words. In this article, I will write a program to count number of words
in a given string and file.

Steps to count number of words

1. Pass the string as input.
2. Using while loop searches the empty space in a given string.
3. If you found space, set the flag true.
4. If the flag is true then increment word counter by 1.

See the below code,

In below code, I am executing while loop until not getting the null character of the given string. In this loop, I am searching space between the word in given string and if I will find the space then make the flag true.

If the flag is true and next character is not empty, then increment the word counter.

 

If you love online courses, then here is a good c language course for you from the Pluralsight, 10 days trial is Free.

C tutorial

C Program to Count Number of Words in a given string

In this example code, I am counting the word in a given string using the above-described function followed by described steps. You can see the string”Welcome to aticleworld”, it contains three words.

 

C Program to Count Number of Words in a given file

In this example code, I am creating a text file “Info.txt” and writing into the string “Welcome to aticleworld”. When the file has been created successfully then open the file in reading mode and read the all the string which has been written into the file at the time of the file creation.

Store the all the read data into the buffer and use the function (wordCounter) to count the number of words.

 



Leave a Reply