C program to count occurrence of a word in a string - My CS Tutorial - My CS Tutorial

Breaking

Programming languages full tutorial and programs, exam papers, visual basic( Vb.net ), information of new technologies and more....

Sunday, January 26, 2020

C program to count occurrence of a word in a string - My CS Tutorial

C program to count or find occurrence of a substring in a string.
In this tutorial we will discuss to write a c program that count the occurrence of a word in a string.
In this program firstly user enter a string in which minimum one word is repeate more than one times.
Then the user enter a substring or a word than the compiler print the occurrence of that word.
Occurrence is numbers of repetenc of a word or substring.



Source Code


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
 int sublen,len,i,count=0;
 char str[100],subst[30],tempst[30];
 clrscr();
 printf("\n ENTER A STRING OR SENTENCE:\n ");
 gets(str);
 printf("\n ENTER A SUBSTRING TO FIND OCCURANCES:\n ");
 gets(subst);
 len=strlen(str);
 sublen=strlen(subst);
 if(len>=sublen)
 {
  for(i=0;i<len;i++)
  {
   strncpy(tempst,str+i,sublen);
   
   tempst[sublen]='\0';
   
   if(strcmp(subst,tempst)==0)
   
       count++;
  }
  
  printf("\n GIVEN SUBSTRING OCCURED %d TIMES:\n ",count);
 }
 else
 {
  printf("\n ENTERED SUBSTRING IS MORE THEN GIVEN STRING:\n ");
 }

getch();
}


OUTPUT:





Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.If you have any method of this program or want to give any suggestion send email on hc78326@gmail.com

Created by-- HARSH CHAUHAN

No comments:

Post a Comment