利用strstr函数判断子字符串在字符串中出现的次数

如题

实现find_sub_string(str1,str2)函数,判断字符串str2在str1中出现的次数。返回str2在str1中出现的次数。

Input:
3
abcdefg
bcd
abcdcdc
cdc
aaaaa
aaa

Output:
1
2
3

 

#include <stdio.h>
#include <string.h>

int find_sub_string(const char* str1,const char* str2)
{

    if(!strstr(str1,str2)) return 0;
    
    int num = 0;
    while(*str1)
    {
        if(strstr(str1,str2) != NULL)
            num++;      //判定为子字符串,次数加一
        else    break;
        str1 = strstr(str1,str2)+1;    
 /*strstr返回子字符串开始位置,然后位置后移一位,重新判断*/
        for(*str1; *str1 !='\0'; str1++)
        {
            if(*str1 == *str2)
                break;
        }
    }
    return num;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char str1[100]={};
        char str2[100]={};
        scanf("%s",str1);
        scanf("%s",str2);
        int num = find_sub_string(str1,str2);
        printf("%d\n",num);
    }
}

 

posted on 2018-05-10 23:33  南笺  阅读(2112)  评论(0编辑  收藏  举报

导航