在替换从文本文件中读取的单词的程序中,如何解释不同的单词长度?
How can I account for varying word lengths in a program that replaces words read from a text file?
我正在尝试用单词 "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);
}
非常感谢任何提示!谢谢:)
改变处理文本的方式。对于您读取的每个块,对于要审查的每个输入词,执行 strstr
。找到 minimum - 即最早的删失词。将块划分为词前、词和词后部分。发出词前部分。跳过单词部分。重复单词后的部分,直到需要新块。
创建一个临时输出 char
大小为 4096 的数组(假设行长度不超过 4096)用于存储完整的处理行。如果你从文件中逐字逐句地阅读会更好。
将读取的单词与每个可替换单词(Ophelia、draw 或 or)进行比较,如果不需要替换,则将该单词附加到带有空格的输出字符数组中。如果必须替换单词,则将单词 CENSORED
附加到输出字符数组。
如果到达新行 printf
整个输出 char
数组,重复使用输出数组并重复该过程,直到到达 EOF
我正在尝试用单词 "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);
}
非常感谢任何提示!谢谢:)
改变处理文本的方式。对于您读取的每个块,对于要审查的每个输入词,执行 strstr
。找到 minimum - 即最早的删失词。将块划分为词前、词和词后部分。发出词前部分。跳过单词部分。重复单词后的部分,直到需要新块。
创建一个临时输出 char
大小为 4096 的数组(假设行长度不超过 4096)用于存储完整的处理行。如果你从文件中逐字逐句地阅读会更好。
将读取的单词与每个可替换单词(Ophelia、draw 或 or)进行比较,如果不需要替换,则将该单词附加到带有空格的输出字符数组中。如果必须替换单词,则将单词 CENSORED
附加到输出字符数组。
如果到达新行 printf
整个输出 char
数组,重复使用输出数组并重复该过程,直到到达 EOF