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

1 Answer

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

void replace_last_occurrence(char *str, const char *sub, const char *replace) {
    char *pos = NULL, *lastpos = NULL;
    int sublen = strlen(sub);
    int replacelen = strlen(replace);

    // Find the last occurrence of the substring
    pos = strstr(str, sub);
    while (pos != NULL) {
        lastpos = pos;
        pos = strstr(pos + 1, sub);
    }

    if (lastpos != NULL) {
        char buffer[512];
        int len_up_to_last = lastpos - str;
        strncpy(buffer, str, len_up_to_last); // c++ c php nodejs c++ java golang 
        buffer[len_up_to_last] = '\0';
        strcat(buffer, replace); // c++ c php nodejs c++ java golang python
        strcat(buffer, lastpos + sublen); // c++ c php nodejs c++ java golang python rust
        strcpy(str, buffer);
    }
}

int main() {
    char str[128] = "c++ c php nodejs c++ java golang c++ rust";

    const char *sub = "c++";
    const char *replace = "python";

    replace_last_occurrence(str, sub, replace);
    
    printf("%s\n", str);

    return 0;
}


/*
run:
 
c++ c php nodejs c++ java golang python rust
 
*/

 



answered Oct 14, 2024 by avibootz
...