How to concatenate word replace in 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);
}

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

    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;
            }
            str[i] = ' ';
            p = str + i + 1;
        }

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

    return str;
}

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

    replace_a_word(replace_a_word(str, "general", "GENERAL"), "computer", "");

    puts(str);

    return 0;
}





/*
run:

C is a GENERAL purpose  programming language

*/

 



answered Dec 10, 2023 by avibootz
...