How to replace a word in a string with C

1 Answer

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

void _replace(char* p, char str[], const char word[], const char replacement[], int i) {
    char* tmp = p + strlen(word);
    
    strcpy(p, replacement);
    p = p + strlen(replacement);
    str[i] = ' ';
    
    if (strlen(word) == strlen(replacement)) return;

    strcat(p, tmp);
}

void replace_a_word(char str[], const char word[], const char replacement[]) {
    if (strlen(replacement) > strlen(word)) return;

    char* p = str;

    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ' ') {
            str[i] = '\0';
            if (strcmp(p, word) == 0) {
                _replace(p, str, word, replacement, i);
                return;
            }
            str[i] = ' ';
            p = str + i + 1;
        }

        if (strcmp(p, word) == 0) { // to replace the last word
            _replace(p, str, word, replacement, i);
        }
    }
}

int main(void)
{
    char str[] = "C is a general-purpose computer programming language";

    replace_a_word(str, "general-purpose", "os");

    puts(str);

    return 0;
}





/*
run:

C is a os computer programming language

*/

 



answered Jul 30, 2022 by avibootz
edited Jul 30, 2022 by avibootz
...