用char做字符串替換


//將串s1中的子串s2替換成串s3
char* replace(char*s1,char*s2,char*s3=NULL)
{
    char *p,*from,*to,*begin=s1;
    int c1,c2,c3,c;         //串長度及計數
    c2=strlen(s2);
    c3=(s3!=NULL)?strlen(s3):0;
    if(c2==0)return s1;     //注意要退出
    while(true)             //替換所有出現的串
    {
        c1=strlen(begin);
        p=strstr(begin,s2); //出現位置
        if(p==NULL)         //沒找到
            return s1;
        if(c2>c3)           //串往前移
        {
            from=p+c2;
            to=p+c3;
            c=c1-c2+begin-p+1;
            while(c--)
                *to++=*from++;
        }
        else if(c2<c3)      //串往后移
        {
            from=begin+c1;
            to=from-c2+c3;
            c=from-p-c2+1;
            while(c--)
                *to--=*from--;
        }
        if(c3)              //完成替換
        {
            from=s3,to=p,c=c3;
            while(c--)
                *to++=*from++;
        }
        begin=p+c3;         //新的查找位置
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM