What is the method in C language for replacing a specific string?

There are several common methods for replacing a specified string in the C language.

  1. Replace a string by another string
  2. replace()
#include <stdio.h>
#include <string.h>

void strreplace(char *str, const char *old, const char *new) {
    char *pos, temp[1000];
    int index = 0;
    int old_len = strlen(old);
    
    while ((pos = strstr(str, old)) != NULL) {
        strcpy(temp, str);
        index = pos - str;
        str[index] = '\0';
        strcat(str, new);
        strcat(str, temp + index + old_len);
    }
}

int main() {
    char str[1000] = "Hello, World! This is a test.";
    char old_str[] = "test";
    char new_str[] = "example";
    
    printf("Before replace: %s\n", str);
    strreplace(str, old_str, new_str);
    printf("After replace: %s\n", str);
    
    return 0;
}

The output is:

Before replace: Hello, World! This is a test.
After replace: Hello, World! This is a example.
  1. You can use loops and character arrays to traverse the string, compare each character, and replace them one by one. Here is an example code:
#include <stdio.h>
#include <string.h>

void strreplace(char *str, const char *old, const char *new) {
    int i, j, k;
    int str_len = strlen(str);
    int old_len = strlen(old);
    int new_len = strlen(new);
    
    for (i = 0; i <= str_len - old_len; i++) {
        if (strncmp(str + i, old, old_len) == 0) {
            for (j = i, k = 0; k < new_len; j++, k++) {
                str[j] = new[k];
            }
            i += new_len - 1;
        }
    }
}

int main() {
    char str[1000] = "Hello, World! This is a test.";
    char old_str[] = "test";
    char new_str[] = "example";
    
    printf("Before replace: %s\n", str);
    strreplace(str, old_str, new_str);
    printf("After replace: %s\n", str);
    
    return 0;
}

The output is the same as the method mentioned above.

The choice of which method to use for replacing strings depends on specific needs and programming habits.

bannerAds