I'm trying to replace words that are passed in with the word "CENSORED" but I can't figure out where to account for the difference between the replaced word and censored. Here's an example of the input and output.
./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?
But the correct output should be:
Said Hamlet to CENSORED,
I'll CENSORED a sketch of thee,
What kind of pencil shall I use?
2B CENSORED not 2B?
Full code:
#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);
}
I really appreciate any tips! Thanks :)
Create a temporary output char
array of size 4096 (assuming line length doesn't exceeds 4096) for storing a complete processed line. It would be better if you read word by word from the file.
Compare the read word with each of the replaceable words (Ophelia, draw, or), if it doesn't need to be replaced append the word to the output char array with a whitespace. If the word has to be replaced then append the word CENSORED
to the output char array.
If you reach a new line printf
the entire output char
array, reuse the output array and repeat the process until you reach EOF