How to replace the first occurrence of a substring in a string with C

1 Answer

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

void replaceFirstOccurrence(char *str, const char *oldSub, const char *newSub) {
    char buffer[1024] = "'"; // Temporary buffer to hold the result
    char *pos = strstr(str, oldSub); // Find the first occurrence of oldSub

    if (pos != NULL) {
        // Copy the part before the oldSub into the buffer
        size_t lenBefore = pos - str;
        strncpy(buffer, str, lenBefore);
        buffer[lenBefore] = '\0';

        // Append the newSub to the buffer
        strcat(buffer, newSub);

        // Append the part after the oldSub to the buffer
        strcat(buffer, pos + strlen(oldSub));

        // Copy the modified string back to the original string
        strcpy(str, buffer);
    }
}

int main() {
    char str[64] =  "aa bb cc dd ee cc";
    const char *oldSub = "cc";
    const char *newSub = "YY";

    replaceFirstOccurrence(str, oldSub, newSub);
    
    printf("%s\n", str);

    return 0;
}



/*
run:

aa bb YY dd ee cc

*/

 



answered Jul 20, 2025 by avibootz
...