从给定字符串中删除单词

问题描述 投票:0回答:1

作为我的家庭作业,我一直在尝试编写代码以从输入的字符串中删除单词。但是,事情是输出的“修改”字符串永远不会真正被修改,而实际上总是输出输入的字符串。我是字符串的新手,所以我对string.h库函数的工作方式不完全了解。

    #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);

    }
c c-strings
1个回答
0
投票

添加以下内容:

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;
}

您应该使用memmove()(也写在您的帖子评论上。)

参考:this thread of SO

© www.soinside.com 2019 - 2024. All rights reserved.