1. 程式人生 > >C:countOfSubstring 查詢子串出現次數

C:countOfSubstring 查詢子串出現次數

//查詢子串出現次數(15分)
// 返回字串s中出現子串substring的次數
// jsdkabcejifabcfjeabckjef  abc
size_t countOfSubstring(const char * s, const char * sub)
{
    if (s==NULL||sub==NULL) {
        return -1;
    }
    
    int count=0;
    const char *sub_temp=sub;
    
    while (*s!='\0') {
        while (1) {
            if (*s++!=*sub++) {
                break;
            }
            if (*sub=='\0') {
                count++;
                s--;
            }
        }
        
        sub=sub_temp;
    }
    
    return count ;
}