7.07.2012

Search Sub String

Q. Write a C program to accept two string from user and find sub string from main string.


For example:


main string: This is a good program
sub string: is
result: 2


Ans.


/*c program to find how many times sub string found in main string*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
 int i,j,count=0;
 char str[40],fstr[10];
 printf("Enter main string: ");
 gets(str);
 printf("Enter sub string: ");
 gets(fstr);
 for(i=0; str[i]!='\0'; i++)
 {
  if(str[i]==fstr[0])
  {
   for(j=0; str[i]==fstr[j] && fstr[j]!='\0'; i++,j++);
   if(fstr[j]=='\0')
      count++;
  }
 }
 printf("%d",count);
 getch();
 return 0;
}


/***************Output***************/


Output of search sub-string from main string C program
Screen shot of find sub-string in main string C program

Related programs:

  1. Reverse all string
  2. Reverse all words but not string
  3. Reverse each first character of word & add extra word
  4. Display string vertically
  5. Change title case of string
  6. Position and repetition of character in string
  7. Search sub string individual from main string

No comments:

Post a Comment