求C语言大神帮忙!采用顺序存储结构,计算一个子串在一个字符串中出现的次数,如果该子串不出现则为0。
这是我写的程序,大神帮忙看看哪里错了啊,有时候调试出来的结果不准确#include"string.h"#include"stdio.h"#include"stdlib.h...
这是我写的程序,大神帮忙看看哪里错了啊,有时候调试出来的结果不准确
# include "string.h"
# include "stdio.h"
# include "stdlib.h"
#define MAXSTRLEN 256
typedef char string[MAXSTRLEN];
int counter(string &s,string t,int c)
{ int n,m,i,j;
n = strlen(s); m = strlen(t);
for(i=0;i<n;i++)
{int k=i;
for(j=0;j<m;)
if(s[k++]!=t[j++]) break;
else if(s[k++]==t[j++]&&k-i==m-1) c++;
}
return c;
}
void main()
{string s,t;int count;
gets(s);gets(t);
count=counter(s,t,0);
printf("出现的次数为%d",count);
printf("\n");
system("pause");
} 展开
# include "string.h"
# include "stdio.h"
# include "stdlib.h"
#define MAXSTRLEN 256
typedef char string[MAXSTRLEN];
int counter(string &s,string t,int c)
{ int n,m,i,j;
n = strlen(s); m = strlen(t);
for(i=0;i<n;i++)
{int k=i;
for(j=0;j<m;)
if(s[k++]!=t[j++]) break;
else if(s[k++]==t[j++]&&k-i==m-1) c++;
}
return c;
}
void main()
{string s,t;int count;
gets(s);gets(t);
count=counter(s,t,0);
printf("出现的次数为%d",count);
printf("\n");
system("pause");
} 展开
1个回答
展开全部
#include <stdio.h>
#include <string.h>
int find(char * str1, char * str2)
{
int i,j;
int str1len=strlen(str1),str2len=strlen(str2);
int count=0;
for(i=0;i<str1len-str2len+1;i++)
{
for(j=0;j<str2len;j++)
{
if(str2[j]!=str1[i+j])
break;
}
if(j==str2len)
count++;
}
return count;
}
int main()
{
char a[200],b[200],*g;
int c=0;
printf("请输入主串:");
gets(a);
printf("请输入子串:");
gets(b);
c=find(a,b);
printf("出现的次数:%d\n",c);
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询