How to write a minimal implementation of Python’s str.replace() in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * replace_str - Replace all occurrences of 'old_sub' with 'new_sub' in 'str'.
 * Returns a newly allocated string (caller must free it).
 */
char *replace_str(const char *str, const char *old_sub, const char *new_sub) {
    if (!str || !old_sub || !new_sub) return NULL;
    if (*old_sub == '\0') return strdup(str); // Avoid infinite loop

    size_t str_len = strlen(str);
    size_t old_len = strlen(old_sub);
    size_t new_len = strlen(new_sub);

    // Count occurrences of old_sub
    size_t count = 0;
    const char *tmp = str;
    while ((tmp = strstr(tmp, old_sub)) != NULL) {
        count++;
        tmp += old_len;
    }

    // Allocate memory for new string
    size_t new_str_len = str_len + (new_len - old_len) * count + 1;
    char *result = malloc(new_str_len);
    if (!result) return NULL;

    // Build the new string
    const char *src = str;
    char *dst = result;
    while ((tmp = strstr(src, old_sub)) != NULL) {
        size_t bytes_to_copy = tmp - src;
        memcpy(dst, src, bytes_to_copy);
        dst += bytes_to_copy;
        memcpy(dst, new_sub, new_len);
        dst += new_len;
        src = tmp + old_len;
    }
    strcpy(dst, src); // Copy the remainder

    return result;
}

int main() {
    const char *text = "Hello World, I'm from Mars! World!?";
    const char *old_word = "World";
    const char *new_word = "Universe";

    char *replaced = replace_str(text, old_word, new_word);
    if (replaced) {
        printf("Original: %s\n", text);
        printf("Replaced: %s\n", replaced);
        free(replaced);
    } else {
        printf("Memory allocation failed.\n");
    }

    return 0;
}

  
  
/*
  
Original: Hello World, I'm from Mars! World!?
Replaced: Hello Universe, I'm from Mars! Universe!?
  
*/

 



answered Mar 9 by avibootz

Related questions

...