Linux C对字符串中对部分子串的查找和替换

/*********************************************************************************
* fine name   :respacestr

* description : respace some characters  from a string.
* author         : hiland    email: pengsor@gmail(dot)com
* license         : GPL
********************************************************************************

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

char * respacestr(char * sdev,char * strs,char * strr)
{
    char * p;
    int lens = strlen(strs),lenr;
    int len;
    int slen = strlen(sdev);
    if(strr == NULL) lenr = 0;
    else lenr = strlen(strr);

len    = lenr - lens;
    while((p = strstr(sdev,strs))!=NULL){
        printf("%d - %s\n",slen,sdev);
        if(len > 0) {    //替换的文字比原来的长,则要扩堆。 比如 用"UUU" 替换"ui"。以防原来空间不够
            sdev = (char *)realloc(sdev,slen+len);
            p = strstr(sdev,strs);
            memmove(p+lenr,p+lens,strlen(p+lens));
            memcpy(p,strr,lenr);
        } else if(len == 0) {
            memcpy(p,strr,lenr);       
        } else {
            memmove(p+lenr,p+lens,strlen(p+lens));
            if(lenr!=0)    memcpy(p,strr,lenr);       
        }
        slen +=len;
    }
    *(sdev+slen) = 0;
    return sdev;

}

int main(int argc,char * argv[])
{
    char sdev[] = "abcdefghiyuijklmnopqryuistuvwxyyuizyuiE";
    char * pdet;
    char * p ;
    if(argc > 2) {
        fprintf(stderr,"usage argc error\n");
        exit(1);
    } else if(argc == 2){
        p = argv[1];
    } else if(argc == 1) {
        p = NULL;
        printf("P==NULL\n");
    }
    pdet = malloc(sizeof(sdev));
    strcpy(pdet,sdev);
    printf("%s\n",pdet);
    pdet = respacestr(pdet,"yui",p);

printf("%s\n",pdet);

return 0 ;

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwsdjz.html