一开始比较懵逼,有想法不知道怎么具体实现,就一步步探索;在csdn逛了几圈只找到一个可行的算法,大佬的文章
感觉有点繁琐
就照着最初的想法终于敲出来了
暂时还没有找到更简单的算法,希望大佬多多指点
#include<stdio.h>
#include<string.h>
int main()
{
/*有想法就应该坚持下去*/
//初始化
char string[100];
gets(string);
int len;
len=strlen(string);
strlwr(string);
char word[8];
gets(word);
//
char temp[100];//建立临时数组来存每一个单词
int i=0;
int an=0;//记录答案
int step=0;//指针要移动的位数
int sum=0;
for (char *p=string;*p!='\0';p=p+step)//注意指针的移动,考虑每次循环后的目的
{
step=0;
for (char*s=p;*s!=' '; ++s)
{
if(s-string>len) break;//此处我改了半个小时才确定,记住这个位置
temp[i]=*s;
i++;
step++;
}
temp[i]='\0';
step++;
sum+=step;
//printf("#%s",temp);
/*要多调试*/
if (!(strcmp(temp,word)))
{
an++;
strcpy(temp," ");//清空数组的小技巧
i=0;
}
else{
i=0;
strcpy(temp," ");
}
}
//考虑一种特殊情况,从刚才那跳出来说明最后一个单词还没统计
strcpy(temp," ");
i=0;
for(char*last=string+sum;*last!='\0';last++)
{
temp[i]=*last;
i++;
}
if (!(strcmp(temp,word)))
{
an++;
}
printf("%s %d",word,an);
return 0;
}