关于字符串查找的问题
求子串在父串中出现的次数
#include <stdio.h>
#include <string.h>
int main()
{
char * pstr1 = "hehelalalahehe";
char * psub = "hehe";
printf("%d\n",caculate(pstr1,psub));
}
int caculate(char *str,char *substr)
{
char * pstr = str;
char * psub = substr;
int times = 0;
while(*pstr != '\0')
{
if(*pstr == *psub)
{
pstr++;
psub++;
if(*psub == '\0')
{
psub = substr;
times++;
}
}
else
{
pstr++;
}
return times;
}
}
请问为何我在调试的时候,执行到if(*psub == '\0')
就直接return times了?问题出在哪里
(正确输出结果是2,但实际为0)
[解决办法]
while(*pstr != '\0')
{
if(*pstr == *psub) //以你的为例 这里成立进入if
{
pstr++;
psub++;
if(*psub == '\0') //此时*psub不为'\0' 跳过这个if
{
psub = substr;
times++;
}
//跳过上面的if就到这
} //继续向下到这外面的if结束
else //if else 结构执行if,不用在再执行else
{
pstr++;
}
//跳过else到这
return times; //然后你就return了times的值还是初值0
}
[解决办法]
//"hehehe"包含1个"hehe"的代码
int caculate(char *str, char *substr)
{
char * pstr = str;
char * psub = substr;
int times = 0;
while (*pstr != '\0')
{
if (*pstr == *psub)
{
pstr++;
psub++;
if(*psub == '\0')
{
psub = substr;
times++;
}
}
else
{
psub = substr;//这里
pstr++;
}
}
return times;//这里
}
//"hehehe"包含2个"hehe"的代码
int caculate(const char *str, const char *substr)
{
int times = 0;
while (*str != '\0')
{
const char *pstr = str;
const char *psub = substr;
do
{
if (!*psub)
{
++times;
}
} while (*pstr++ == *psub++);
++str;
}
return times;
}