有关字符串的三种操作

来源:互联网 发布:网络大白兔是什么意思 编辑:程序博客网 时间:2024/06/06 00:50

去掉字符串两端空格

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;} 
原创粉丝点击