我有一个代码,它将删除句子中第一个出现的单词:

#include "stdio.h"
#include "string.h"

int delete(char *source, char *word);

void main(void) {

    char sentence[500];
    char word[30];



    printf("Please enter a sentence. Max 499 chars. \n");
    fgets(sentence, 500, stdin);

    printf("Please enter a word to be deleted from sentence. Max 29 chars. \n");
    scanf("%s", word);

    delete(sentence, word);

    printf("%s", sentence);
}


int delete(char *source, char *word) {

    char *p;
    char temp[500], temp2[500];

    if(!(p = strstr(source, word))) {
        printf("Word was not found in the sentence.\n");
        return 0;
    }

    strcpy(temp, source);
    temp[p - source] = '\0';
    strcpy(temp2, p + strlen(word));
    strcat(temp, temp2);
    strcpy(source, temp);
    return 1;
}

如何修改它以删除给定句子中出现的所有单词?在这种情况下,我还能使用strstr函数吗?
谢谢你的帮助!
对完全不同的方法也持开放态度。
这听起来像是一个家庭作业问题,但实际上是一个过去的期中问题,我想解决它,为我的期中考试做准备!
作为一个附带问题,如果我使用fgets(word, 30, stdin)而不是scanf("%s", word),它将不再工作,并告诉我在句子中找不到这个词。为什么?

最佳答案

如何修改它以删除给定句子中出现的所有单词?
正如你所建议的,有很多方法,而且既然你对完全不同的方法也持开放态度。。。
这里有一个不同的想法:
句子用空格分隔单词。你可以用它来帮助解决这个问题。考虑使用fgets()strtok()strcat()来实现这些步骤,以分离字符串,并在不移除字符串的情况下重新组装它。

0)  create line buffer sufficient length to read lines from file
    (or pass in line buffer as an argument)
1)  use while(fgets(...) to get new line from file
2)  create char *buf={0};
3)  create char *new_str; (calloc() memory to new_str >= length of line buffer)
4)  loop on buf = strtok();, using " \t\n" as the delimiter
Inside loop:
    a. if (strcmp(buf, str_to_remove) != 0) //approve next token for concatenation
            { strcat(new_str, buf); strcat(new_str, " ");}//if not str_to_remove,
                                                  //concatenate token, and a space
5)  free allocated memory

new_str现在包含不出现str_to_remove的句子。
下面是一个使用这一组步骤的演示(差不多)
int delete(char *str, char *str_to_remove)
{
    char *buf;
    char *new_str;

    new_str = calloc(strlen(str)+1, sizeof(char));

    buf = strtok(str, " \t\n");
    while(buf)
    {
        if(strcmp(buf, str_to_remove) != 0)
        {
            strcat(new_str, buf);
            strcat(new_str, " ");
        }
        buf = strtok(NULL, " \t\n");
    }
    printf("%s\n", new_str);
    free(new_str);
    getchar();

    return 0;
}

int main(void)
{
    delete("this sentence had a withh bad withh word", "withh");
    return 0;
}

关于c - 删除C语言中一个句子中所有单词出现的功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26615780/

10-12 00:12
查看更多