c - Find substring in a string -
here code find substring entered user in 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, return true, else false int main(void) { printf("%d", find_str("abcdef", "cde")); /* return true in case */ printf("%d", find_str("abcde", "cde")); /* return false in case */ }
as explained in comment, returns true whenever ends additional characters. if not, returns false. think there problem in increment/decrement operator. not find how?
this because code decides stop on finding \0
after performing comparison
*str++ == *++a
this condition true
when match happens @ end of string on null terminators, while
loop happily proceed beyond end of both strings past null terminator, causing undefined behavior.
changing condition exit when *a
0 should fix problem:
while((*str++ == *++a) && (*a));
Comments
Post a Comment