子字符串查找——C语言

    华为的一道比较基础的面试题,就是查找一个字符串中某个子字符串出现的次数,并只考虑最左对齐的情况。

    如在"helloejesjhelloejedjshhello"中查找子字符串"hello"出现的次数。

    最直接的方法是使用遍历实现。

int string_find( char str[], char substr[] )
{
    int i, j, check ,count = 0;
    int len = strlen( str );        /*取得字符串长度,不包括'\0'*/
    int sublen = strlen( substr );
    for( i = 0; i < len; i++ )
    {
        check = 1;        /*检测标记*/
        for( j = 0; j + i < len && j < sublen; j++ )        /*逐个字符进行检测,在sublen长度内,一旦出现不同字符便将check置为0*/
        {
            if( str[i + j] != substr[j] )
            {
                check = 0;
                break;
            }
        }
        if( check == 1 )        /*在sublen长度内的字符都相等*/
        {
            count++;
            i = i + sublen;        /*调整检测起始位置*/
        }
    }
    return count;
}

    

原文地址:https://www.cnblogs.com/liangchao/p/2678878.html