我正处于准备考试的阶段,我最不自豪的是我的弦乐技巧。我需要做的是从句子中删除一个词,而不使用 <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/