Write a function, substr_count , that counts the occurrences of the subString “c
ID: 2079485 • Letter: W
Question
Write a function, substr_count, that counts the occurrences of the subString “class” in an input string, srcString.
#include <stdio.h>
#include <string.h> //YOU CAN USE STRING LIBRARY Functions here
// Count the number of occurrences of “class” in srcString
int substr_count(char *srcString, char *subString)
{
//YOUR CODE HERE
}
int main(void)
{
char srcString[200] = ""; //empty string
char subString[8] = "class"; //substring
int get_count = 0;
scanf("%s", srcString); //get a string from input keyboard
get_count = substr_count(srcString, subString);
printf("%s occurs %d times in %s ", subString, get_count, srcString);
}
Explanation / Answer
#include <stdio.h>
#include <string.h>
int substr_count(const char *srcString, const char *subString)
{
int countOccurence = 0 ;
size_t sub_len = strlen(subString) ;
const char *p= srcString ;
while(p= strstr(p,subString))
{
++countOccurence ;
p+=sub_len;
}
return countOccurence;
}
int main(void)
{
char srcString[200]= "" ;
char subString[] = "mystring";
int get_count= 0;
scanf("%199s",srcString); //setting limit
get_count = substr_count(srcString , subString);
printf("%s occurs %d times in %s ", subString, get_count, srcString);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.