c语言的子串出现次数

题目10;子串出现次数
八个英文长句,事先存放于字符数组中。输入一个单词判断该单词在长句中出现了几次。区分大小写。
如: In the _end, it's_ not the _years in your. life _that _count. (表示空格输入: the, 输出: the 在本句出现了2次。
输入: THE, 输出: THE 在本句出现了0次。

 

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

int main(void)
{
    const char *str = ": In the _end, it's_ not the _years in your. life _that _count.", *pstr;
    char substr[32];
    int cnt = 0;

    scanf("%s", substr);
    //len = strlen(substr);
    pstr = strstr(str, substr);
    while (pstr) {
        cnt++;
        pstr = strstr(pstr+1, substr);
    }

    printf("cnt = %d\n", cnt);
    return 0;
}

供参考~

尝试使用strstr函数~

遍历就可以了啊,找到第一个匹配字符,然后后面逐个匹配,全部相同则加1

代码如下,字符串你自己替换一下就可以了

#include <stdio.h>
#include <string.h>
#include <ctype.h>
//查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
void findstr(char*big ,char* smal,int pos[],int *nmb)
{
	int i,j,lenb,lens;
	lenb = strlen(big);
	lens = strlen(smal);
	*nmb = 0;
	if(lens > lenb)
		return;

	i = 0;
	while(i < lenb-lens+1)
	{
		for (j = 0; j < lens;j++)
		{
			if(tolower(big[i+j]) != tolower(smal[j]))
				break;
		}
		if (j == lens) //说明找到
		{
			pos[*nmb] = i;
			(*nmb)++;
			i += lens;
		}else
			i++;
	}
}


int main()
{
	int nmb = 0,i;
	char fat[8][100] ={"In the _end","it's_ not the _years in your."," life _that _count","a test","hellow world","it's time","hellow haha","go go go"};
	char sun[100] = {0};
	int pos[50] = {0};

	
	printf("请输入需要查找的单词:");
	gets(sun);
	for (i = 0;i<8;i++)
	{
		nmb = 0;
		findstr(fat[i],sun,pos,&nmb);
		printf("%s在%s中出现的次数:%d\n",sun,fat[i],nmb);
	}
	
	return 0;
}

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632