In: Computer Science
In C: Find a string within a string Given two strings S1 & S2, search for an occurrence of the second string within a first string. Note: Do not use system library for the implementation. Input: Code Zinger University Zinger where, First line represents string S1. Second line represents string S2. Output: 5 Here 'Zinger' word starts at 5th index within 'Code Zinger University’. Assume that, The length of strings S1 & S2 are within the range [1 to 10000]. Character comparisons will be case-sensitive.
If you have any doubts, please give me comment...
#include <stdio.h>
#define MAX_SIZE 10000
int findSubstrIndex(char S1[], char S2[]);
int main()
{
char S1[MAX_SIZE], S2[MAX_SIZE];
int index;
printf("Enter String1: ");
scanf("%[^\n]s", S1);
printf("Enter String2: ");
scanf("\n%[^\n]s", S2);
index = findSubstrIndex(S1, S2);
if (index == -1)
printf("%s not found!\n", S2);
else
printf("%s found at index %d\n", S2, index);
return 0;
}
int findSubstrIndex(char S1[], char S2[])
{
int i = 0, j;
while (S1[i] != '\0')
{
if (S1[i] == S2[0])
{
int exists = 1;
j = 1;
while (S2[j] != '\0')
{
if (S2[j] != S1[i + j])
{
exists = 0;
break;
}
j++;
}
if (exists){
return i;
}
}
i++;
}
return -1;
}