C语言求大神解答,在一句话中查找一个单词的出现次数

#include<stdio.h>intste_d(char*a,char*b);voidmain(){intsum;chara[100],b[10];printf("p... #include<stdio.h>
int ste_d(char *a,char *b);
void main()
{
int sum;
char a[100],b[10];
printf("please input the sentence\n");
gets(a);
printf("please input the word\n");
fflush(stdin);
gets(b);
sum=ste_d(a,b);
printf("%d\n",sum);
}
int ste_d(char *a,char *b)
{
int s=0;
while(*a!='\0')
{
if(*b==*a)
{
for(;*b!='\0'&&*a!='\0';a++,b++)
{
if(*b!=*a)
break;
if(*(b+1)=='\0')
s++;
}
a--;
}
a++;
}
return s;
}
展开
 我来答
风雷九州
2015-01-07 · TA获得超过3026个赞
知道大有可为答主
回答量:1127
采纳率:100%
帮助的人:473万
展开全部

在函数ste_d里面b都++了,怎么还能判断第二次出现呢


并且单词出现的话,后面应该是空格才对,ste_d更改如下

int ste_d(char *a,char *b)
{
    int s=0;
    char *temp;

    while(*a!='\0')
    {
        if(*b==*a)
        {
            temp = b;
            for(;*temp!='\0'&&*a!='\0';a++,temp++)
            {
                if(*temp!=*a)
                    break;
            }
            /* temp到末尾了并且a是空格或者结束才是完整的单词 */
            if(*temp=='\0' && (*a==' '||*a=='\0'))
            {
                s++;
            }
            continue;
        }
        a++;
    }
    return s;
}

 

楼上的答案是错误的,如果输入是这个样子的话


please input the sentence

abc ab ab abc

please input the word

ab

4

寒寒家
推荐于2016-12-02 · TA获得超过2921个赞
知道大有可为答主
回答量:1482
采纳率:100%
帮助的人:2042万
展开全部
//错误在于,没有回溯
//在代码里做了修改,并注释,有疑问,欢迎交流
#include<stdio.h>
int ste_d(char *a,char *b);
void main()
{
int sum;
char a[100],b[10];
printf("please input the sentence\n");
gets(a);
printf("please input the word\n");
fflush(stdin);
gets(b);
sum=ste_d(a,b);
printf("%d\n",sum);
}
int ste_d(char *a,char *b)
{
int s=0;
char *tmp_org_ptr = a;
char *tmp_b = b;//保存起始位置
while(*a!='\0')
{
if(*b==*a)
{
tmp_org_ptr = a; //这里要保存之前的位置
for(;*b!='\0'&&*a!='\0';a++,b++)
{
if(*b!=*a)
break;
if(*(b+1)=='\0')
s++;
}
a = tmp_org_ptr; //回溯
b = tmp_b;
}
a++;
}
return s;
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式