c - 从句子(字符串)中删除一个词

标签 c

我正处于准备考试的阶段,我最不自豪的是我的弦乐技巧。我需要做的是从句子中删除一个词,而不使用 <string.h>图书馆。 这是我到目前为止所得到的。它一直显示某些变量未声明,例如开始和结束。

#include <stdio.h>

/* Side function to count the number of letters of the word we wish to remove */
int count(char *s) {
    int counter = 0;
    while (*s++) {
        counter++;
        s--;
    return counter;
}

/* Function to remove a word from a sentence */
char *remove_word(const char *s1, const char *s2) {
    int counter2 = 0;
    /* We must remember where the string started */
    const char *toReturn = s1;
    /* Trigger for removing the word */
    int found = 1;
    /* First we need to find the word we wish to remove [Don't want to
      use string.h library for anything associated with the task */
    while (*s1 != '\0') {
        const char *p = s1;
        const char *q = s2;
        if (*p == *q) 
           const char *start = p;
        while (*p++ == *q++) {
            counter2++;
            if (*q != '\0' && counter2 < count(s2))
                found = 0;
            else {
                const char *end = q;
            }
        }
        /* Rewriting the end of a sentence to the beginning of the found word */
        if (found) {
            while (*start++ = *end++)
               ;
        }
        s1++;
    }
    return toReturn;
}

void insert(char niz[], int size) {
    char character = getchar();
    if (character == '\n')
        character = getchar();
    int i = 0;
    while (i < size - 1 && character != '\n') {
        array[i] = character;
        i++;
        character = getchar();
    }
    array[i] = '\0';
}

int main() {
    char stringFirst[100];
    char stringSecond[20];

    printf("Type your text here: [NOT MORE THAN 100 CHARACTERS]\n");
    insert(stringFirst, 100);
    printf("\nInsert the word you wish to remove from your text.");
    insert(stringSecond, 20);
    printf("\nAfter removing the word, the text looks like this now: %s", stringFirst);

    return 0;
}

最佳答案

你的代码格式错误,我强烈建议编译: gcc -ansi -Wall -pedantic -Werror -D_DEBUG -g (或类似的)

  • 首先在函数 block 的开头声明您的变量,它们仅在声明它们的 block 内是已知的。

  • 您的计数函数有问题,缺少结束符“}”(无法编译) 应该是这样的

    size_t Strlen(const char *s)
    {
        size_t size = 0;
        for (; *s != '\n'; ++s, ++size)
        {}
        return size;
    }
    
  • 实现 memmove 比逐个字符复制更有效

关于c - 从句子(字符串)中删除一个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596609/

相关文章:

c - 子剪辑 : add revision no in file

c - 在非递归数组中填充多行的不寻常方法?

c - 我如何从 boot.local 执行我的 exe 文件

c - 简化 C 中的嵌套 for 循环

将 ASCII 字符数组转换为十六进制字符数组

c - 如何获取Linux系统的正常运行时间?

c - 在源代码级别使用 GCC __builtin_object_size 是否有任何动机?

c - 使用Wifi模块ESP8266发送UDP广播消息

c - 使用 IN/OUT 标志每行显示一个字符串

无法将字符串分配给 C 中的扑克牌程序的单个字符变量