C Program to find substring of a string
Program
#include <stdio.h>
int search(char [], char []);
void main()
{
int loc;
char source_str[20];
char sub_str[20];
printf("Enter a string:\n");
scanf(" %s", source_str);
printf("Enter sub-string to search:\n");
scanf(" %s", sub_str);
loc = search(source_str, sub_str);
if (loc == -1)
printf("String not found\n");
else
printf("Found from start location %d\n", loc + 1);
}
int search(char source_str[], char sub_str[])
{
int i, j, firstOcc;
i = 0, j = 0;
while (source_str[i] != '\0')
{
while (source_str[i] != sub_str[0] && source_str[i] != '\0')
i++;
if (source_str[i] == '\0')
return (-1);
firstOcc = i;
while (source_str[i] == sub_str[j] && source_str[i] != '\0' && sub_str[j] != '\0')
{
i++;
j++;
}
if (sub_str[j] == '\0')
return (firstOcc);
if (source_str[i] == '\0')
return (-1);
i = firstOcc + 1;
j = 0;
}
}
Output
Enter a string:
Bengaluru
Enter sub-string to search:
galu
Found from start location 4