C语言:下面图片上的题目怎么写才能过关?

2025-01-27 13:58:28
推荐回答(3个)
回答1:

代码文本:

#include "stdio.h"

#include

int find_str(const char *pa,const char *pb){

int n;

for(n=0;pa=strstr(pa,pb);n++,pa++);

return n;

}

int main(int argc,char *argv[]){

char a[81],b[81];

printf("Enter 2 strings(Separated by a ' ' or 'Enter')...\n");

scanf("%80s%80s",a,b);

printf("Find time(s) = %d\n",find_str(a,b));

return 0;

}

回答2:

#include

#include

int find_str(char *str1,char *str2)

{

    int cnt;

    char *p;

    for(cnt=0;*str1;str1++)

    {

        if((p=strstr(str1,str2))!=NULL)

        {

            cnt++;

            str1=p;

        }

    }

    return cnt;

}

int main()

{

    char str1[1000],str2[1000];

    while(scanf("%s %s",str1,str2)==2)

    {

        printf("find times = %d\n",find_str(str1,str2));

    }

    return 0;

}

回答3:

不用string函数库,自己造轮子:
#include
int find_str(const char*s1,const char*s2)
{
int len1=0,len2=0,count=0;
while (s1[len1]) len1++; //len1=strlen(s1)
while (s2[len2]) len2++; //len2=strlen(s2)
for (int i=0;i<=len1-len2;i++)
{
int tmp=1;
for (int j=0;j {
if (s2[j]!=s1[i+j])
{
tmp=0;
break;
}
}
count+=tmp;
}
return count;
}
int main()
{
char str1[0x100], str2[0x100];
scanf("%s %s", str1, str2);
printf("find times = %d\n", find_str(str1, str2));
return 0;
}