
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;
} 展开
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;
} 展开
展开全部
在函数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
展开全部
//错误在于,没有回溯
//在代码里做了修改,并注释,有疑问,欢迎交流
#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;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |