/* * search for a pattern in a string * returns the position where the pattern appears * if no pattern appears, return -1 * eg: pattern "BBBA", str "ABBABBBAC" return 4 */ int search_pattern(char* pattern, char* str) { int s_len = 0, p_len = 0, i = 0, j = 0; p_len = strlen(pattern); s_len = strlen(str); while(i < s_len) { while(j < p_len && i + j < s_len) { /* match each character in the pattern * if any mismatch occurs, the loop will break */ if(pattern[j] != str[i + j]) break; j++; } /* pattern matched */ if(j == p_len) return i; /* if the pattern didn't match, increase counter in * original string, reset counter in pattern to 0 */ i++; j = 0; } return -1; }