Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You already learned how to write a program to count the number of words in a str

ID: 3771493 • Letter: Y

Question

You already learned how to write a program to count the number of words in a string. Can you write a C program to count the occurrences of a fixed word in a string? So if the string is “This is the last question.”, and the word we need to count is “is”, then the ouput should be 1. But notice we do not need to count the substring “is” in word “This”. The basic structure of program countWord.c has been provided below. And in this program, the string is defined in the main function and the word should be inputted by user.

Hint: record the words (substring) by splitting the string with whitespace ‘ ’(implement your own code because no library function in C is provided to split a string); check if the word in string equals to the input through library function strcmp(take care of the return value) .

#include …

#include …

int main(void)

{

            char str[]=”This is the last question”;

            char word[10]; // initialize it from input

Explanation / Answer

#include<stdio.h>
#include <string.h>
int main()
{
char str[] ="is This is the islast is is question";
//char str[20];
//strcpy(str,'This is the last question');
char word[10]; // initialize it from input
scanf("%s",word);
printf("Entered %s ",word);
char* token = strtok(str, " ");
int count=0;
while (token) {
if(strcmp(token,word) == 0)
count++;
printf("token: %s ", token);
token = strtok(NULL, " ");
}
printf(" count of "%s" in given string =%d",word,count);

return 0;
}