Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思想:一个一个匹配,注意终止条件;要相对严格限制
- char *strStr(char *haystack, char *needle) {
- int i=0;
- int hlen = strlen(haystack);
- int nlen = strlen(needle);
- while(i<=hlen-nlen) {
- char *p = haystack;
- char *q = needle;
- while(*p!='\0' && *p == *q) {
- p++;
- q++;
- }
- if(*q=='\0') {
- return p-(q-needle);
- } else {
- haystack++;
- i++;
- }
- }
- return NULL;
- }