我有这段代码可以从句子中删除第一次出现的单词:
#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)
,它将不再有效并且告诉我在句子中找不到这个词。为什么?
最佳答案
尝试以下操作
#include <stdio.h>
#include <string.h>
size_t delete( char *source, const char *word )
{
size_t n = strlen( word );
size_t count = 0;
if ( n != 0 )
{
char *p = source;
while ( ( p = strstr( p, word ) ) != NULL )
{
char *t = p;
char *s = p + n;
while ( ( *t++ = *s++ ) );
++count;
}
}
return count;
}
int main( void )
{
char s[] = "abxabyababz";
printf( "%zu\n", delete( s, "ab" ) );
puts( s );
return 0;
}
输出是
4
xyz
关于fgets
的问题,就是在字符串中包含换行符。您必须将其从字符串中删除。
关于c - C语言删除句子中所有出现的单词的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615780/