Here is my code to find substring entered by the user in the given string.
bool find_str(char *str, char const *substr) {
while(*str) {
if(*str++ == *substr) {
char const *a = substr;
while((*str++ == *++a)); /*empty*/
if(*a == '\0')
return true;
}
}
return false;
}
// If match found, then return true, else false
int main(void) {
printf("%d", find_str("ABCDEF", "CDE")); /* Return true in this case */
printf("%d", find_str("ABCDE", "CDE")); /* Return false in this case */
}
As explained in the comment, it returns true whenever it ends with an additional characters. If it is not, then it returns false. I think there is a problem in increment/decrement operator. But I could not find how?
strstrdoes this - 10 seconds google-foo and you can find implementations e.g. opensource.apple.com/source/xnu/xnu-792.13.8/libsa/strstr.c . In your code, there's several bugs: to learn to find them, I recommend putting trace likeprintf("'%s' =?= '%s'\n", str, a);where you're doing your comparisons... you'll pretty soon see what you're really comparing and realise what's wrong, then you can reason and experiment to fix it. Hint: as Apple did, keep the is-the-a-match-here logic separate from look-everywhere-along-str:strncmp.