C - check if string is a substring of another string
- by user69514
I need to write a program that takes two strings as arguments and check if the second one is a substring of the first one. I need to do it without using any special library functions. I created this implementation, but I think it's always returning true as long as there is one letter that's the same in both strings. Can you help me out here. I'm not sure what I am doing wrong:
#include <stdio.h>
#include <string.h>
int my_strstr( char const *s, char const *sub ) {
char const *ret = sub;
int r = 0;
while ( ret = strchr( ret, *sub ) ) {
if ( strcmp( ++ret, sub+1 ) == 0 ){
r = 1;
}
else{
r = 0;
}
}
return r;
}
int main(int argc, char **argv){
if (argc != 3) {
printf ("Usage: check <string one> <string two>\n");
}
int result = my_strstr(argv[1], argv[2]);
if(result == 1){
printf("%s is a substring of %s\n", argv[2], argv[1]);
} else{
printf("%s is not a substring of %s\n", argv[2], argv[1]);
}
return 0;
}