我有这段代码,它将删除句子中第一次出现的单词:
#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)
,它不再起作用并告诉我在句子中找不到这个词。为什么?