字符串模型

//char *p = "11abcd111222abcd33322abcd";
//求字符串p中 abcd出现的次数
//1 请自定义函数接口,完成上述要求
//2 自定义的业务函数 和 main函数必须分开

下列代码,找了很久的bug最后终于找到

while(p = strstr(mystr,mysample))
{
ncount++;
p = p + strlen(mysample);
}
while(*p == '\0')
{
break ;
}

程序卡死在while(p = strstr(mystr,mysample))

strstr判断出mystr中mysample是否出现,并返回mysample第一次出现的位置。

但是上述代码一直查询的是mystr,mystr的指向并没有改变,虽然把判断后的地址返回出来了,但是没有用上啊!!

故修改后的代码为:

while(mystr = strstr(mystr,mysample))
{
ncount++;
mystr = mystr + strlen(mysample);
}
if(*mystr == '\0')
{
break ;
}

完整代码

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


//char *p = "11abcd111222abcd33322abcd";
//求字符串p中  abcd出现的次数
//1 请自定义函数接口,完成上述要求
//2 自定义的业务函数 和 main函数必须分开

int getCount(char * str,char * sample, int *ncount)
{
    int tmpcount = 0;
    char *mystr = str;
    char *mysample = sample;
    int ret = 0;
    
    if(mystr == NULL || mysample == NULL || ncount == NULL)
    {
        ret = -1;
        printf("func getCount() err: %d (mystr == NULL || mysample == NULL || ncount == NULL) \n", ret);
        return ret;
    }

    while(mystr = strstr(mystr,mysample))
    {
        tmpcount++;
        mystr = mystr + strlen(mysample); //指针达到下次查找条件
    }
    while(*mystr == '\0')
    {
        break ;
    }
    
    *ncount = tmpcount; //间接赋值是指针存在的最大意义
        
    return ret;
}
//return 应该返回错误代码

int main(void)
{
    int ret;
    int count = 0;
    char *p = "11abcd111222abcd33322abcd";
    char *simple = "abcd";

    ret = getCount(p,simple,&count);
    if(ret != 0)
    {
        printf("function getCount() err: %d\n", ret);
        return ret;
    }
    printf("count = %d\n ", count);

    return ret;
}

 

posted @ 2017-04-26 21:56  Liu_Jing  Views(280)  Comments(0)    收藏  举报