c - 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
解决方案
搜索单词并用您要保留的部分覆盖它:
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
”放入输入的第二行,只是一个空格 - 这里格式化程序显然吃了那个空间,这就是为什么它现在用下划线标记),但在现实生活中,您必须注意单词周围的空格(通常可以删除其中一个)和标点符号(以后可能需要也可能不需要)。
推荐阅读
- perl - 在 curses 库中绑定 return 和 esc 键(在 perl 中)
- emacs - 将 flycheck 与 compile_commands.json 一起使用
- rxjs - Rxjs - refCount 变为 0 后出现意外的 publishReplay + refCount 行为
- android-studio - java.lang.RuntimeException:编译时无法启动活动 ComponentInfo,“,”附近的语法错误
- android - Android Studio Cmake构建错误:向量类型之间的无效转换
- php - MyBB find_replace_templatesets 不工作
- python - Python写入文件使用不必要的存储?
- java - 为什么我的循环在计算最后一个数字之前就跳出来了?
- unit-testing - 酶:wrapper.find('SickButton').simulate('click') 没有点击
- regex - 谷歌表格:正则提取