【问题标题】:How can I account for varying word lengths in a program that replaces words read from a text file?如何在替换从文本文件中读取的单词的程序中解释不同的单词长度?
【发布时间】:2016-07-23 10:56:15
【问题描述】:

我正在尝试用“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);
}

我非常感谢任何提示!谢谢:)

【问题讨论】:

    标签: c string algorithm file-io file-read


    【解决方案1】:

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

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

    如果您到达新行 printf 整个输出 char 数组,请重新使用输出数组并重复该过程,直到到达 EOF

    【讨论】:

      【解决方案2】:

      更改处理文本的方式。对于您阅读的每个块,对于要审查的每个输入单词,执行strstr。找到 minimum - 即最早被删减的词。将块分为词前、词和词后部分。发出单词之前的部分。跳过单词部分。重复单词后的部分,直到需要一个新的块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        • 2014-08-25
        • 2017-12-02
        • 2018-08-15
        • 1970-01-01
        相关资源
        最近更新 更多