有关字符串的三种操作

去掉字符串两端空格

int trimSpace(const char *inbuf, char *outbuf)
{
    int count = 0;
    int i = 0, j = 0;

    char *p = inbuf;
    j = strlen(p) -1;
    if(NULL==inbuf || NULL==outbuf)
    {
        printf("NULL==inbuf || NULL==outbuf  err\n");
        return -1;
    }
    while (isspace(p[i]) && p[i] != '\0')//从前往后 
    {
        i++;
    }

    while (isspace(p[j]) && j>0)//从后往前 
    {
        j--;
    }
    count = j-i +1;
    printf("除去空格有%d个字符\n", count);
    //将从p1往后的size_t个字符拷贝到p中 
    memcpy(outbuf, inbuf+i, count); 
    outbuf[count] = '\0';
    return 0;
}

字符串反转

//
int str_fz(char *str)
{
    char *p1,*p2;
    char c;
    int reg=0;
    if(NULL==str)
    {
        reg=-1;
        printf("str_fz(NULL==str):%d\n",reg);
        return reg;
    }
    p1=str;
    p2=p1+strlen(str)-1;
    while(p1<p2)
    {
        c=*p2;
        *p2=*p1;
        *p1=c;
        p1++;
        p2--;
    }
    return reg; 
}

计算一个字符串中子字符串个数

//
int CalcStr1_to_str2(char *str1,char *str2,int *mycount)
{
    int count=0;
    char *p=str1;
    if(NULL==str1||NULL==str2||NULL==mycount)
    {
        printf("CalcStr1_to_str2 err\n");
        return -1;
    }
    while(*p!='\0')
    {
        p=strstr(p,str2);
        if(p!=NULL)
        {
            count++;
            p=p+strlen(str2);
        }
        else
        {
            break;
        }
    }
    *mycount=count; 
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值