首页 > 解决方案 > Erasing the word string from another sentence string if it includes it

问题描述

I'm creating 2 strings. The first is a sentence, the second is a word. If the sentence contains the word, we erase it from the sentence.

I've tried it in several ways but it always gives the correct answer if the word is at the end of the sentence.

char sntc[150];
char word[30];

gets(sntc);
gets(word);

char temp[50];
int i=0;
int index=0;

while (i<strlen(sntc);) {
        for(; sntc[i] != '\0'; i++) {
                if(sntc[i] == ' ' || sntc[i] == '\0') {
                        break;
                }
                temp[index++]=sntc[i];
        }
        temp[index]='\0';
        if (strcmp(temp, word) == 0) {
                i++;
                index=0;
                continue;
        } else {
                printf("%s ", temp);
                i++;
                index=0;
        }
}

For this input:

merhaba dunyali nasilsin
dunyali

the expected output is:

merhaba nasilsin

标签: carraysstringc-strings

解决方案


搜索单词并用您要保留的部分覆盖它:

char *found;
while((found=strstr(sntc,word))!=NULL)
  strcpy(found,found+strlen(word));

当然,您可以存储strlen(word)在变量中。
测试:https ://ideone.com/BpLRe3

如果您担心宇宙的终结,请使用memmove(也可以使用fgets,即使您不担心也适用)。它们都需要一些工作,因为fgets还存储了必须处理的换行符(否则strstr会寻找类似的东西word\n,可能是徒劳的),同时memmove移动内存,因此必须明确告知大小,并且它有包括空终止符:

char sntc[150];
char word[30];
char *found;
size_t wordlen;
fgets(sntc,sizeof(sntc),stdin);
fgets(word,sizeof(word),stdin);
wordlen=strlen(word)-1;
word[wordlen]=0;
while((found=strstr(sntc,word))!=NULL)
  memmove(found,found+wordlen,strlen(found+wordlen)+1);
printf("%s",sntc);

测试中仍然应用了空格技巧:https ://ideone.com/hvZAtm (我已经将“ _dunyali”放入输入的第二行,只是一个空格 - 这里格式化程序显然吃了那个空间,这就是为什么它现在用下划线标记),但在现实生活中,您必须注意单词周围的空格(通常可以删除其中一个)和标点符号(以后可能需要也可能不需要)。


推荐阅读