【程序设计】
题目:函数str_count统计子字符串substr在字符串str中出现的次数,如果substr在str中不出现,
则返回值0。请完成该函数。
样例:
母串=ABCDabcd1234+-*/XYZxyz/ABCDabcd1234+-*/Aa1 ABCDabcd
待计数子串=123
子串在母串中共出现2次
请按任意键继续. . .
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
/**********Program**********/
int str_count(char *substr,char *str)
{
int count=0,i,j,flag=0;
char *p1=str;//子串头检索指针,在母串上从头到尾移动
int len2=strlen(substr),len1=strlen(str);
for(;*p1!='\0';)
{
flag=0;
if(*p1==substr[0])//匹配子串的头,匹配上了再去看子串后面能不能也对上
{
char *p2=substr,*p0=p1;
for(;*p2!='\0';p2++)
{
if(*p2!=*p1)
{
flag=1;
p1=p0;//子串身体不匹配,那么头检索指针要回到之前匹配好的“子串头”位置
//如果匹配,那么本if语句不执行,头检索指针将跳到这个子串的尾部的后一个位置,进行非重叠阅读
break;
}
p1++;
}
if(!flag)
count++;
}
p1++;//上一个“验明正身”,是假的,那么要去下一个;
}
return count;
}
/********** End **********/
void main(void)
{
char ss[100];
char *s="ABCDabcd1234+-*/XYZxyz/ABCDabcd1234+-*/Aa1 ABCDabcd";
cout<<"母串="<<s<<endl;
cout<<"待计数子串=";
cin.getline(ss,99);
cout<<"子串在母串中共出现"<<str_count(ss,s)<<"次"<<endl;
}