怎么改都改不过来,自己感觉思路没有问题,但是为什么前两次输入结果是错的,求大家解答

#include <stdio.h>
#define N 100
void subString(char a,charb)
{
int count=0;
char *temp;
temp=b;
while(*a)
{
while(*a==*temp)
{
a++;
temp++;
}
if(*temp=='\0')
{
count++;
temp=b;
}
if(*a!=*temp)
a++;
}
printf("%d\n",count);
}
int main(int argc, char *argv[])
{
char a[N];
gets(a);
char b[N];
gets(b);
subString(a,b);
return 0;
}

img

因为最后一次的时候 while(*a)没有执行,最后的时候,a和temp同时到字符串尾了(也就是*a=='\0', *temp == '\0'的这种情况),这种情况下你少算了一次。

img

代码修改如下:

#include <stdio.h>
#define N 100
void subString(char *a,char *b)
{
    int count=0;
    char *temp,*tt;
    temp=b;
    while(1)
    {
        tt = a;
        while(*tt==*temp)
        {
            if(*tt=='\0') break;
            tt++;
            temp++;
        }
        if(*temp=='\0')
        {
            count++;
            if(*tt=='\0') break;

            temp = b;
            a = tt;
        }else
        {
            if(*tt=='\0') break;
            temp = b;
            a++;
        }
        
    }
    printf("%d\n",count);
}
int main(int argc, char *argv[])
{
    char a[N];
    gets(a);
    char b[N];
    gets(b);
    subString(a,b);
    return 0;
}

最后一个if加个else