C Program to Find Substring from String

C Program to Find Substring from String

Write C Program to Find Substring from String

// C Program to Find Substring from String

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	char S1[50], S2[15];
	int index, i, l1, l2, j, max;

	printf("Enter String :--> ");
	gets(S1);

	printf("Enter Substring :--> ");
	gets(S2);

	l1 = strlen(S1);
	l2 = strlen(S2);
	max = l1 - l2;

	for(i = 0;i <= max; i++)
	{
		if(strncmp(S1 + i, S2, l2) == 0)
            /* here a and b is considered as array address and
            a+i means array is compared with array b
            upto the size of substring */
			break;
	}
	if(i <= max)
		printf("\nSubstring is located at index --> %d", i);
	else
		printf("\nSubstring not found");

	return 0;
}

Output:

Run 1:
Enter String :--> Hello CodeCrucks
Enter Substring :--> Code

Substring is located at index --> 6

Run 2:
Enter String :--> Hello CodeCrucks
Enter Substring :--> Python

Substring not found