Checking the string for a given substring
If the substring is found, the program will print the index within the string where the substring has been found.
Program:
#include<stdio.h>
#define MAX 50
int main()
{
char str[MAX], search[MAX];
int length1 = 0, length2 = 0, i, j, flag=0;
printf("Enter the string at the most %d characters long:",MAX-1);
gets(str);
printf("You entered:");
puts(str);
printf("Enter the substring that you want to search:");
gets(search);
printf("You entered:");
puts(search);
for(i=0; str[i]!='\0'; i++)
{
length1++; //Counting the length.
}
printf("\nThe length of the first string is : %d\n",length1);
for(i=0; search[i]!='\0'; i++)
{
length2++; //Counting the length.
}
printf("\nThe length of the (sub)string is : %d\n",length2);
if(length2>length1) return 0;
int position = -1;
for (i = 0; i <= length1 - length2; i++)
{
for (j = i; j < i + length2; j++)
{
flag = 1;
if (search[j - i] != str[j] )
{
flag = 0;
break;
}
}
if (flag == 1){
position=i;
break;
}
}
if (flag == 1)
printf("Substring found at index : %d",position);
else
printf("Substring not found");
return 0;
}
Output:

Using strstr from string.h
#include <string.h>
char *strstr(const char *string1, const char *string2);
Program:
#include <stdio.h>
#include <string.h>
#define MAX 50
int main()
{
char str[MAX], search[MAX];
printf("Enter the string at the most %d characters long:",MAX-1);
gets(str);
printf("You entered:");
puts(str);
printf("Enter the substring that you want to search:");
gets(search);
printf("You entered:");
puts(search);
char* p;
// Find first occurrence of s2 in s1
p = strstr(str, search);
int position=0;
// Prints the result
if (p) {
printf("String found\n");
printf("Printing the pointer returned by strstr: %s\n", p);
position = p - str;
printf("Substring was found at index : %d", position);
}
else
printf("Substring not found\n");
return 0;
}
Output:

Note:
The strstr() function finds the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process.
The strstr() function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, the strstr() function returns NULL. If string2 points to a string with zero length, the strstr() function returns string1.
To find the index, here we have done pointer subtraction, subtracting the pointer to the first element from the pointer returned by strstr() .

