c - C语言删除句子中所有出现的单词的函数

标签 c string

我有这段代码可以从句子中删除第一次出现的单词:

#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/

相关文章:

c++ - 嵌入式文件作为 char 数组的编译器问题

javascript - 将整个字符串中的大写字母替换为小写字母和连字符

c - 如何在 posix_openpt() 中定义名称

vb.net - 如何: streamreader in csv file splits to next if lowercase followed by uppercase in line

php - 如何从字符数组中找到字符串匹配项?前任。给定 a,n,t 在单词列表中查找字符串匹配 ant, an, tan

javascript - 匹配更多可能性的正则表达式(javascript)

java - 无法从 Cmd 类型对非静态方法 getVideoURL() 进行静态引用

c - C 中这些类型和声明的含义是什么?

c++ - 锁定和操作需要很长时间

c - 指针太困惑了 : Stack with singly linked list in C