C Language Daily Challenge No. 15: Implementing a String Replacement Function

📌 Problem Description

Write a function str_replace that replaces the first occurrence of an old substring with a new substring in the given string, returning the modified new string.

Requirements:

  • Only a single replacement is required

  • The returned new string must be dynamically allocated

Example:

Input: str="Hello World", old="World", new="C"  Output: "Hello C"  

Difficulty: ⭐️ (suitable for learners mastering pointers and basic memory management)

💡 Basic Implementation (Dynamic Memory Allocation Method)

#include <stdio.h>#include <string.h>#include <stdlib.h>
char* str_replace(const char* str, const char* old, const char* new) {    // Find the position of the old substring    char* pos = strstr(str, old);    if (!pos) return strdup(str); // Return original string copy if not found
    // Calculate lengths of each part    int front_len = pos - str;          // Length before old substring    int old_len = strlen(old);          // Length of old substring    int new_len = strlen(new);          // Length of new substring    int total_len = strlen(str) + new_len - old_len; // Total length
    // Allocate memory and concatenate strings    char* result = (char*)malloc(total_len + 1);    memcpy(result, str, front_len);                     // Copy front part    memcpy(result + front_len, new, new_len);           // Copy new substring    strcpy(result + front_len + new_len, pos + old_len); // Copy back part    return result;}
int main() {    char* res = str_replace("Hello World", "World", "C");    printf("%s\n", res); // Output: Hello C    free(res); // Free memory    return 0;}

🔥 Key Code Analysis

  1. <span>strstr</span> Find Substring: Finds the position of the first matching old substring

  2. <span>strdup</span> Copy Original String: Returns a copy of the original string directly if the old substring is not found

  3. Three-Part Concatenation:

  • Copy content before the old substring

  • Insert the new substring

  • Copy content after the old substring

⚡ Extended Exercises

Try modifying the code to implement the following features:

  1. Replace all matching substrings

  2. Add parameter checks (e.g., handling null pointers)

  3. Support replacement of Chinese characters

🚀 Next Issue Preview No. 16: Calculating String Length

📢 Interaction Time

  • What other practical string manipulation functions can you think of? Feel free to leave a comment!

  • Vote: What do you think is the most commonly used string operation?

🚀If you find this useful, feel free to share it with friends learningC language!

Article Author:Vv Computer Graduate Examination World (focusing on computer graduate examination guidancefor 8years)

Original Statement: Please contact for authorization to reprint, infringement will be pursued.

Leave a Comment