Possible Duplicate:
Is there a reverse fn() for strstr
I wrote this main and function that get two string and check if the second string exist within the first one,
then return the most right index appear place.
If wasn't found return -1
.
This is the code I wrote:
#include <stdio.h>
int strindex(char[], char[]);
int main()
{
char a[100];
char b[100];
int search;
printf("Enter two strings, To search the second one in the first one:\n");
printf("Enter the first string to search in:\n");
fgets(a,100,stdin);
printf("Enter the second string to search in the first:\n");
fgets(b,100,stdin);
printf("\n\n THE FIRST STRING IS:%s\n\n THE SEARCH STRING IS:%s",a, b);
printf("\n\n");
search = strindex(a, b);
if(search==-1)
printf("The second String didnt found in the first string\n");
else printf("The second string appear in the first string at most right at index:%d\n",search);
return 0;
}
int strindex(char s[], char t[])
{
int foundIndex = -1;
int tempFound, startNext;
int i,j;
i = j = 0;
while (s[i]!='\0')
{
if(s[i]==t[j])
{
startNext = i+1;
tempFound = i;
while(s[i]!='\0' && t[j]!='\0' && s[i]==t[j])
i++,j++;
if (t[j]=='\0') /**check if it null**/
{
printf("found match");
foundIndex = tempFound;
}
i = startNext;
j = 0;
}
else i++;
}
return foundIndex;
}
I think I have a problem in this line:
if (t[j]=='\0') /**check if it null**/
cause I tried put two string that the second one contain in the first but although t[j]
is equal to null it doesn't perform the inside if statement.
- I know there are many other ways of writing this program. But I know this one should work too and i am trying to make it work.