Find whether the given sub-string present in the string, & print the index if it does else print -1( without using library function )
For example:
If the given main string is : "coderegister" and the sub-string is "reg",
Then the output should be the index of the first occurrence of the sub-string in the main string which is '4' here.
If the given main string is: "coderegister" and the sub-string is "service"
Then the output should be '-1'
Implementation:
For example:
If the given main string is : "coderegister" and the sub-string is "reg",
Then the output should be the index of the first occurrence of the sub-string in the main string which is '4' here.
If the given main string is: "coderegister" and the sub-string is "service"
Then the output should be '-1'
Implementation:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *m,*s;
int flag=1,fla=1;
int i,j,k,index;
/* Allocate memory for input string in which we have to search for a substring */
m=(char*)malloc(sizeof(char)*256);
/* Allocate memory for sub-string to search in the main string */
s=(char*)malloc(sizeof(char)*256);
/* Get the main string from the user */
scanf("%s",m);
/* Get the sub-string from the user */
scanf("%s",s);
/* Loop until we reach end of the main string */
for(i=0;*(m+i);i++)
{
flag=1;
fla=1;
/* Find the first character match of the sub-string and the main string */
if(*(m+i)==*s)
{
/* If there is a match, store the current index in 'index' variable */
index=i;
/* Temporary counter variable to start from the first character matching
index till end of the sub-string */
k=i;
/* Loop until the end of sub-string */
for(j=0;*(s+j);j++,k++)
{
/* If any one character doesn't match, set the flag to zero and break the inner loop */
if(*(m+k)!=*(s+j))
{
flag=0;
break;
}
}
/* If the flag is still set to '1' then, all the characters of the sub-string matches
a part of string in main string */
if(flag)
{
/* Print the starting index of such a match */
printf("%d",index);
/* Set fla varaiable to '0' to mark that we found atleast one match */
fla=0;
break;
}
}
}
/* If there are no matches of sub-string in the main string, print '-1' */
if(fla)
printf("-1");
return 0;
}