C string replacement

C string replacement

  The C language does not provide a well-written string replacement function, and needs to be written by combining functions such as string search, string copy, and string splicing. The sample code is as follows:

// 将strRes中的from替换为to,替换成功返回1,否则返回0。
int StrReplace(char strRes[],char from[], char to[]) 
{
    
    
    int i,flag = 0;
    char *p,*q,*ts;
    for(i = 0; strRes[i]; ++i) 
    {
    
    
        if(strRes[i] == from[0]) 
        {
    
    
            p = strRes + i;
            q = from;
            while(*q && (*p++ == *q++));
            if(*q == '\0') 
            {
    
    
                ts = (char *)malloc(strlen(strRes) + 1);
                strcpy(ts,p);
                strRes[i] = '\0';
                strcat(strRes,to);
                strcat(strRes,ts);
                free(ts);
                flag = 1;
            }
        }
    }
    return flag;
}

Guess you like

Origin blog.csdn.net/qq_35308053/article/details/118101860