C语言统计相同字符串个数

不知道哪里有逻辑错误,其中s是原始字符串abcabc,s1是要搜索的部分abc
int fun(char *s,char *s1)
{
int n=0;
char *p=NULL;
while(*s)
{
p=s1;
for(;(*p)&&(*p==*s);s++,p++)
{
if(*p==0)
n++;
}
}
return n;
}
求解决谢谢,给其他算法也行。我觉得我的也差不多了只是有一点错误
int fun(char *s,char *s1)
{
int a=0;
char *p=NULL;
p=s1;
while(*s)
{
p=s1;
for(;(*p)&&(*p==*s);s++,p++);//确认相同
if(*p==0)
{
a++;
}
}
return a;
}
这个有时正确有时错误

1.可通过 strstr 函数,查找子字符串。找到后即非空,然后加上子字符串偏移,再进行查找没,直到最后返回为空。

2.char *strstr( const char *str1, const char *str2 );

功能:函数返回一个指针,它指向字符串str2 
首次出现于字符串str1中的位置,如果没有找到,返回NULL。

#include <stdio.h>
#include <string.h>

// ä»Žstr1中查找str2的个数,并返回
int findChildCnt(char* str1, char* str2)
{
    int len = strlen(str2);
    int cnt = 0;
    while (str1 = strstr(str1, str2)) // å¦‚果查找到,则执行循环,否则为空退出循环
    {
        cnt++; // ç»Ÿè®¡æ¬¡æ•°
        str1 += len; // åŠ ä¸Šåç§»é‡ï¼Œå³ç§»é™¤str2
    }
    return cnt;
}

int main()
{
    char str1[100], str2[100];
    printf("intput str1 :");
    gets(str1);
    printf("intput str2 :");
    gets(str2);
    printf("Child Cnt: %d\n", findChildCnt(str1, str2));
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-06-11
while(*s)

 {

  p=s1;

   for(;(*p)&&(*p==*s);s++,p++)

   {

  if(*p==0)

   n++;

   }

    s++ //这里不能忘了 
 }

追问

为什么要加,不加也行。加了也错

追答#include<stdio.h>
int fun(char *s,char *s1)
{
  int n=0;
  char *p=NULL;
 while(*s)
 {
  p=s1;
   for(;*p&&(*p==*s);s++,p++);
   
  if(*p=='\0')
  n++;
  if(*s!=*p)
   ++s;
 }
   return n;
}
void main()
{
 char s[]="abceabc,abc",s1[]="abc";
 printf("%d ",fun(s,s1));
}

追问

还是不行啊,有新的算法吗

追答

无语。。。思想就是这样,我都测试了全是对的,
你说说看,那里不行?

#include
int fun(char *s,char *s1)
{
int n=0;
char *p=NULL;
while(*s)
{
p=s1;
for(;*p&&(*p==*s);s++,p++);
if(*p=='\0')
{n++;s--;} //这里少了一个s--
if(*s!=*p)
++s;
}
return n;
}
void main()
{
char s[]="abcabc",s1[]="abc";
printf("%d ",fun(s,s1));
}

追问

aaaaaaaaaa a

追答

本回答被提问者采纳
第2个回答  2013-09-21
当p和s递增时,*p==*s只能匹配正好结尾相同的。因为*s字符串中间没有"\0"。改写一个靠谱的吧。
第3个回答  2013-09-21
要判断出现相同字符串没那么简单的,也没那么复杂
注意s的动向就行了
#include<stdio.h>
#include<string.h>
int fun(char *s,char *s1)
{
int a=0,l=strlen(s1);
char *ps,*p1=s1;
while(*s)
{
ps=s;
while(1)
{
if(*p1==*ps)
{
p1++;
ps++;
}
else//出现不相等时,p1返回原来位置s1,s长度缩小
{
p1=s1;
s++;
break;
}
if(*p1==0)
{
a++;
p1=s1;
s+=l;
break;
}
}
}
return a;
}
void main()
{
char s[]="abcabcabcdababcd",s1[]="abcd";//结果是2
printf("%d\n",fun(s,s1));
}本回答被网友采纳
第4个回答  2013-09-21
#include<stdio.h>
#include<string.h>
int fun(char *s,char *s1)
{
int n=0;
char *p=NULL;
while(*s)
{
p=s1;
for(;*p&&*p==*s;s++,p++);
if(*p=='\0'){
n++;
s--;
}
s++;
}
return n;
}
void main()
{
char s[]="abcabc",s1[]="abc";
printf("%d\n",fun(s,s1));
}
相似回答