C/C++语言 计算字符串中子字符串出现的次数

任意输入2个字符串,求计算第二个字符串在第一个字符串中出现的次数。
用c++写了程序,但是计算结果不对。求教!

int main(void)
{
char str1[20],str2[20],*p1,*p2;

int sum=0;

cout<<"intput two strings"<<endl;

cin>>str1;
cin>>str2;

p1=str1;
p2=str2;

while (*p1!='\0')
{
if(*p1==*p2)

{ while((*p1=*p2)&&(*p2!='\0'))
{
p1++;
p2++;
}
}

else
p1++;
if(*p2=='\0')
sum=sum+1;

p2=str2;

}

cout<<sum;
return 0;

}

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个回答  推荐于2017-09-28
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
char str1[20],str2[20],*p1,*p2;
int sum=0;
cout<<"intput two strings"<<endl;
cin>>str1;
cin>>str2;
p1=str1;
p2=str2;

while (*p1!='\0')
{
if(*p1==*p2)
{ //while((*p1==*p2)&&(*p2!='\0')&&(*p1!='\0'))
while((*p1==*p2)&&(*p2!='\0')) //有问题
{
p1++; //这里有问题
p2++;
}
}
else p1++;
if(*p2=='\0') sum=sum+1;
p2=str2;
}
cout<<sum;
return 0;

}
-----
例如:输入 ababababab ab
while (*p1!='\0'), if(*p1==*p2),判断都为真,进入 while((*p1==*p2)&&(*p2!='\0')) 循环,对比字串2的每一个字符,并将p1指针后移,当有不相等的字符退出循环,这时再进入这个循环时问题来了,P1的指针被后移了,确没有恢复。只把P2进行了恢复,也许作者认为不必要,但就是这不必要导致了程序出错,while((*p1==*p2)&&(*p2!='\0'))也没有对P1进行判断是否还能继续。
在输入字符串时也要注意,不能大于20个字符。否则要改数组大小。
--------------
修改后:
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
char str1[255],str2[255],*p1,*p2, *temp;
int sum=0;
cout<<"intput two strings"<<endl;
cin>>str1;
cin>>str2;
p1=str1;
p2=str2;

while (*p1!='\0')
{
temp = p1;
if(*temp==*p2)
{

while((*temp==*p2)&&(*p2!='\0')&&(*temp!='\0'))
{
temp++;
p2++;
}
}
p1++;
if(*p2=='\0') sum=sum+1;
p2=str2;
}
cout<<sum;
return 0;

}本回答被提问者采纳
第2个回答  2012-06-03
//还可以简单点
#include<iostream>
using namespace std;
int main()
{
int sum=0;
char sd[4];
char sc[300];
char* pd=sd;
char* pc=sc;
char* temp;
cout<<"enter two string"<<endl;
cin>>sd;
cin>>sc;
while(*pc!='\0')
{
temp=pc;
while(*temp==*pd)
{
temp++;
pd++;
}
if(*pd=='\0')
sum++;
pd=sd;
pc++;
}
cout<<sum;

}
第3个回答  2006-10-11
while((*p1=*p2)&&(*p2!='\0'))
里面把==写成=了,是*p1==*p2

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网