C指针操作——全部替换字符串里某个字符或者某个子串

时间:2021-02-22 20:35:52
#include<string.h>
#include<stdio.h>

#include<stdlib.h>

//把source字符串里所有s1字符全部替换成字符s2

void replace_char(char *result, char *source, char s1, char s2)
{
    int i = 0;
    char *q = NULL;

    q = source;
    for(i=0; i<strlen(q); i++)
    {
        if(q[i] == s1)
        {
            q[i] = s2;
        }
    }
    strcpy(result, q);
}


void replace_string(char *result, char *source, char* s1, char *s2)
{
    char *q=NULL;
    char *p=NULL;
   
    p=source;
    while((q=strstr(p, s1))!=NULL)
    {
        strncpy(result, p, q-p);
        result[q-p]= '\0';//very important, must attention!
        strcat(result, s2);
        strcat(result, q+strlen(s1));
        strcpy(p,result);
    }
    strcpy(result, p);    
}

void main()
{
    char url[64] = "ad12 fdf5 d12f dfd12 dfp";
    char result[64] = {0};
    
    replace_char(result, url, ' ', '_' );//把url里所有‘ ’字符替换成'_'字符,结果存在result中
    printf("char final result=%s\n",result);
    memset(result, 0, sizeof(result));
    replace_string(result, url, "12", "@@@");//把url里所有“12”字符串替换成“@@@”字符串
    printf("string final result=%s\n", result);

}

分别单独运行的结果如下:

测试结果:char final result=ad12_fdf5_d12f_dfd12_dfp

测试结果:string:final result=ad@@@ fdf5 d@@@f dfd@@@ dfp