C/C++ Program to count the number of articles in a string

Write a program to count the number of articles in a string in C/C++.

Example,

Input
An apple a day keeps the doctor away

Output
Number of "a" = 1
Number of "an" = 1
Number of "the" = 1

There are 3 articles in the English language – “a”, “an” and “the”. The problem is very simple. We will use strtok() to read each word of the input string. We then compare each word of the string with “the”, “The”, “a”, “A”, “an”, “An” using strcmp(), and maintain count for each article.

If you don’t know how strtok() works then read this.

Program to count the number of articles in a string

#include<stdio.h>
#include<string.h>

int main() {

	char str[300];
	char *token;
	int c_a,c_an,c_the;
	c_a = c_an = c_the = 0; 
	
	printf("Enter String: ");
	gets(str);
	
	token = strtok(str, " .,");
	
	while(token!=NULL){
		if(strcmp(token, "a")==0 || strcmp(token, "A")==0){
			c_a++;
		}
		else if(strcmp(token, "an")==0 || strcmp(token, "An")==0){
			c_an++;
		}
		else if(strcmp(token, "the")==0 || strcmp(token, "The")==0){
			c_the++;
		}
		token = strtok(NULL, " .,");
	}
	
	printf("Number of \"a\": %d\n", c_a);
	printf("Number of \"an\": %d\n", c_an);
	printf("Number of \"the\": %d\n", c_the);
	
}

Output

Enter String: An apple a day keeps the doctor away
Number of "a": 1
Number of "an": 1
Number of "the": 1

Read

Leave a Comment

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