5.C pointer operation - all replace a character or a substring in a string

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

#include<stdlib.h>

//Replace all s1 characters in the source string with the characters 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, ' ', '_' );//Replace all ' ' characters in url with '_' characters, the result is stored in result
    printf("char final result=%s \n",result);
    memset(result, 0, sizeof(result));
    replace_string(result, url, "12", "@@@");//Replace all "12" strings in the url with " @@@"string
    printf("string final result=%s\n", result);

}

The results of running them separately are as follows:

Test result: char final result=ad12_fdf5_d12f_dfd12_dfp

Test result: string:final result=ad@@@ fdf5 d@@@f dfd@@@ dfp

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857682&siteId=291194637