C program to search a sub string within a string


The sub string search within a given input string is done by checking each and every word of an input string against the sub string. This program checks this by taking sub string into the variable ‘p1’ and input string into the variable ‘p2’. The outer for loop in the function helps to iterate from the start of the input string to the end. While loop iterates from the start of the sub string to the end and checks every character of subs tring against the input string if there is any difference it will come out of the while loop moving to next word in the input string otherwise if it founds a match the function returns the starting address of the sub string. In this way the sub string search is performed on a given string.

C program to sub string search within a string


Source code:

#include<stdio.h>
int main()
{
    char a[50], b[30];
    char *mystrstr(char *, char *);
    printf("\n Enter the string:");
    gets(a);                             //Step 1 
    printf("\n Enter the substring to search:");
    gets(b);                          //Step 1
    if(mystrstr(a,b) == NULL)
       printf("NOT FOUND\n");       //Step 5
    else
       printf("FOUND\n");          //Step 5
  return 0;
}
char *mystrstr(char *input, char *pat)
{
    char *start, *p1, *p2;
    for(start = &input[0]; *start != '\0'; start++)
	{	                        //Step 2
	    p1 = pat;                   
	    p2 = start;
	    while(*p1 != '\0')          //Step 3
		{
		    if(*p1 != *p2)      //Step 3 (i)
			 break;
		    p1++;
		    p2++;
		}
	     if(*p1 == '\0')        //Step 4
		return start;
	}
       return NULL;                  //Step 4
}


edit-code-image

Sample test cases:

1.  Enter the string:topoint is a good souce for programming questions
    Enter the substring to search:good
    FOUND
	
2.  Enter the string:topoint is a good souce for programming questions
    Enter the substring to search: god
    NOT FOUND
 

Explanation for sub string search:

Step 1 : The string and the substring are read from the user using gets().
Step 2 : For loop iterates from the start of the input string until the end of the input string.
Step 3 : This while loop helps to check the substring with the input string until the end of the substring
Step 3(i): If there is mismatch between the characters in the input string and the substring this step helps to come out of the loop and makes ‘p2’ point to the next word in the input string.
Step 4 : If while loop reaches until the ‘\0’ character in the substring then it implies that there is match found in the input string. So function returns the start of that sub string.
Step 5 : Finally the output corresponding to the input is printed on the output screen using printf() function.

Explore C Programs: C Programs
More Information:More Information