0

I have been trying to write a code to remove a word from an inputted string as part of my homework. But the thing is the outputted "modified" string never really gets modified and it actually always outputs the inputted string. I'm new to strings so I don't have a perfect understanding of how the string.h library functions work.

    #include<stdio.h>
    #include<string.h>
    int main(void)
    {

    char str[60], strtemp[60], word[10], * token;
    printf("Enter the sentence: ");
    gets_s(str);
    printf("Enter the word to be deleted: ");
    gets_s(word);

    int i = 0;
    token = strtok(str, " ");
    while (token != NULL) {

        if (!i && token != word)
            strcpy(strtemp, token);

        else if (token == word) {
            token = strtok(NULL, " ");
            continue;
        }

        else {
            strcat(strtemp, " ");
            strcat(strtemp, token);
        }
        token = strtok(NULL, " ");
        i++;
    }

    strcpy(str, strtemp);
    printf("Modified string: %s \n", str);

    }
rev
  • 37
  • 1
  • 5

1 Answers1

0

Add the following:

char *strremove(char *str, const char *sub) {
    size_t len = strlen(sub);
    if (len > 0) {
        char *p = str;
        while ((p = strstr(p, sub)) != NULL) {
            memmove(p, p + len, strlen(p + len) + 1);
        }
    }
    return str;
}

You should use the memmove() (written on your post's comment too.)

Reference: this thread of SO.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • I have added this code and it seems to be working fine but if we were to input the string "Today is a sunny day" and remove the word "day", the output is "To is a sunny". Which isn't really desired. Is there a way to get around this? – rev May 12 '20 at 15:35
  • Also, it would be better if I could solve the problem with strtok if possible and not a custom function. – rev May 12 '20 at 15:36
  • `Today`'s `day` and simply `day`'s `day` are both same. They'll be eliminated for sure. It might get more complicated... – Rohan Bari May 12 '20 at 15:38
  • I see. Would you mind explaining how the function works? – rev May 12 '20 at 15:44
  • @Rohan Bari The function can remove a sub-word instead of a word. So it is incorrect. For example str is equal to "World" and sub is equal to "or" then the result will be "Wld" that is incorrect because str does not contain the word "or". – Vlad from Moscow May 12 '20 at 16:17
  • @VladfromMoscow that's true. The OP asked for words, not removing the occurrences. But one thing, there are many results available in Google results related to OP's criteria. I've just posted one of them. – Rohan Bari May 12 '20 at 16:30