2016-04-04 27 views
2

我试图用单词“CENSORED”替换传入的单词,但我无法弄清楚替换单词和被审查单词之间的区别。这是一个输入和输出的例子。如何解释替换从文本文件中读取的单词的程序中的不同字长?

./a.out Ophelia draw or <poem.txt 
Said Hamlet to CENSORED, 
I'll CENSOREDsketch of thee, 
What kind of pencil shall I use? 
2B CENSORED2B? 

但正确的输出应该是:

Said Hamlet to CENSORED, 
I'll CENSORED a sketch of thee, 
What kind of pencil shall I use? 
2B CENSORED not 2B? 

全码:

#include <assert.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char **argv){ 
char fileRead[4096]; 
char replace[] = "CENSORED"; 
int arg=0; 
size_t word_len = strlen(argv[arg]); 
while (fgets(fileRead, sizeof(fileRead), stdin) != 0) 
{ 
    char *start = fileRead; 
    char *word_at; 
for (arg = 1; arg < argc; arg += 1) { 
if ((word_at = strstr(start, argv[arg])) != 0) { 
     printf("%.*s%s", (int)(word_at - start), start, replace); 
     start = word_at + word_len -1; 
} 
} 
    printf("%s", start); 
} 
    printf("\n"); 
return (0); 
} 

我真的很感激任何提示!谢谢:)

回答

1

创建一个临时输出char大小为4096的数组(假设行长度不超过4096)用于存储完整的处理过的行。如果你从文件中逐字读出,会更好。

将读取的单词与每个可替换单词(Ophelia,draw或or)进行比较,如果不需要替换,则将该单词添加到带有空格的输出字符数组中。如果必须替换该字,请将字CENSORED附加到输出字符数组中。

如果你达到一个新的行printf整个输出char阵列,再用输出数组,直到你到达EOF

重复上述过程
1

改变你处理文本的方式。对于您阅读的每个块,对于每个输入词进行审查,执行strstr。找到最低 - 也就是最早的审查单词。将该块分成词前,词和词后部分。发出单词之前的部分。跳过单词部分。重复这个词后的部分,直到需要新的块。