loong qiang
像风一样自由

字符串朴素匹配法

相等情况

int index(const char * str1, const char * str2, int pos)
{
    int i = pos;
    int j = 0;
       while(i < strlen(str1) && j < strlen(str2))
       {
               if(str1[i] ==  str2[j]) // matched then continue
               {
                          ++i;
                          ++j;
               }
               else     // unmatched then backtrace
               {
                   i = i - j + 1;
                   j = 0;
               }
       }

       if(j >= strlen(str2))  // matched and return the index
            return i-strlen(str2);
       else
            return -1;  // not found
}

不等情况

int index(char *t, char *p, int len1, int len2) {
    int i, j;
    for (i = 0; i < len1; i++) {
        for (j = 0; j < len2; j++) {
            if (p[j] != t[j + i]) {
                break;
            }
        }
        if (j == len2) {
            return i;
        }
    }
    return -1;
}
posted on 2014-07-12 15:26  loong qiang  阅读(289)  评论(0编辑  收藏  举报