RobertD
RobertD

Reputation: 25

Replace each word with another word in a given text in C

I have to make a function which replaces each word (x), with another word(y), in a given text(**string). Can I replace them directly in the given text? Or should I make a new array and make the replacements there? However and don't know how to continue. The code I wrote is:

void operation_2(char x[100], char y[100], char **string, int N)
{
    int len = 0;
    char *word;
    char s[12] = " .,?!\"';:";
    char **newstring = (char **)malloc(N * sizeof(char *));

    for (i = 0; i<= N; i++) {
            word = strtok(string[i], s);
            while (word != NULL) {
                    if (strcmp(word, x) == 0) {
                            len = strlen(string[i]) - strlen(x) + strlen(y);
                            newstring[i] = (char *)malloc((len + 1) * sizeof(char));

Upvotes: 0

Views: 106

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60058

If you create a new string, it'll be able to take any string (string literal, an array on the stack, a static array, an array on the heap) as input, but it won't be as memory efficient.

If you want maximum memory efficiency, then you can modify the target string in-place, but you'll have restrictions depending on where the input string is stored.

  • string literal or possibly a const static array: you can't do anything do anything with it
  • stack, or static: you can shrink it
  • heap: you can realloc it (shrink it or expand it)

The memmove function might come in handy if you decide to modify the string in place.


Keep in mind however, that:

  1. There's no such thing as array arguments in C. They always decay to pointers.
  2. strtok will modify it's input, so you'd need to make at least one copy if you decide to go with strtok

Upvotes: 1

Related Questions