字符串模型几个案例

1 求char *p =abcd112223abcd12321abcd545345353abcd42,求字符串p中abcd出现的次数。

实现方法1:

int main()
{
char *p = "abcd112223abcd12321abcd545345353abcd42";
int cnt = 0;
while (p != NULL)
{
    p = strstr(p, "abcd");
    if (p != NULL)
    {
        cnt++;
        p = p + strlen("abcd");
    }
}
    printf("cnt = %d \n",cnt);
    return 0;
}

实现方法2:

    int findcnt1(char *p, char* substr)
    {
        int cnt = 0;
        while (p != NULL)
        {
            p = strstr(p, substr);
            if (p != NULL)
            {
                cnt++;
                p = p + strlen(substr);
            }
        }
        return cnt;
    }

 int main()
{
    char* str = "abcd112223abcd12321abcd545345353abcd42";
    char *substr = "abcd";
    int cnt = 0;

    cnt = findcnt1(str,substr);

    printf("cnt1 = %d \n", cnt);
    return 1;
}

实现方法3:

int findcnt2(char *p, const char* substr, int *cnt)
{
    char * str = p;
    int tmp = 0;

    if (!p || !substr)
{
    printf("p =NULL || substr == NULL. \n");
    return -1;
}

while (str != NULL)
{
    str = strstr(str, substr);
    if (str != NULL)
    {
        tmp++;
        str = str + strlen(substr);
    }
}

*cnt = tmp;
return 0;
}

int main()
{
    char* str = "abcd112223abcd12321abcd545345353abcd42";
    char* substr = "abcd";
    int cnt2 = 0;
    int ret = 0;
     ret = findcnt2(str, substr,&cnt2);

     if (ret == 0)
         printf("cnt2 = %d \n", cnt2);
     else
         printf("findcnt2 err. \n");
    return 0;
}

2 实现trim函数

int trimSpace(char *inbuf, char **outbuf)
{
    int ret = 0;
    char * p = inbuf;
    int len = strlen(inbuf) -1 ;
    int left =0, right = len;
    char *tmp = NULL;

    if (!inbuf)
    {
        ret = -1;
        printf("inbuf is NULL. \n");
        return -1;
    }

while (p[left] == ' ')
    left++;
while (p[right] == ' ')
    right--;

if (left >= right)
{
    *outbuf = NULL;
    return ret;
}

    *outbuf = (char*)malloc(right - left + 1);
    memset(*outbuf, 0, right - left + 1);
    strncpy(*outbuf, p + left,right - left);
    return ret;
}

int main()
{
    int ret = 0;
    char *inbuf = "   123124    ";
    char *outbuf;
    ret = trimSpace(inbuf,&outbuf);

    if (ret == 0)
        printf("outbuf=%s.\n",outbuf);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值