The goal of this program is to replace given words in redact string into asterisks in a full sentence.
e.g. given a full sentence: "The quick brown fox jumps over the lazy dog" and redact string: "the, jumps, lazy", the output is "*** quick brown fox ***** over *** **** dog", which needs to be saved in a result.txt.
My main idea is to first extract redact string and a full sentence into an array before searching for a word. If it matches, the array of full sentence is replaced with asterisks. Finally, an array is converted back to a string.
The problem of my code is that I want to extract string from fullSentence[] and redactString[] into individual arrays but when I run this code it output...
The jumps, lazy the Y├╠╠╠╠╠╠j
This is the code:
int main(void) {
char fullSentence[] = "The quick brown fox jumps over the lazy dog";
int t = 0;
int i = 0;
char **redactArray = NULL;
char *token = strtok(fullSentence, " ");
char redactString[] = "the, jumps, lazy";
int j = 0;
char *p = strtok (redactString, ", ");
char *extractString[3];
for (t = 1; token; t) { // Extract fullSentence[]
redactArray = realloc(redactArray, t *sizeof(*redactArray));
redactArray[t - 1] = malloc(strlen(token) 1);
strncpy(redactArray[t - 1], token, strlen(token) 1);
token = strtok(NULL, " ");
}
for (i = 0; i < t-1; i){
printf("%s\n", redactArray[i]);
}
while (p != NULL) { // Extract redactString[]
extractString[j ] = p;
p = strtok(NULL, ", ");
}
for (j = 0; j < sizeof(extractString); j) {
printf("%s\n", extractString[j]);
}
return extractString;
}
Thanks in Advance :)
CodePudding user response:
Would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char fullSentence[] = "The quick brown fox jumps over the lazy dog";
char **fullArray = NULL; // tokenized array for fullSentence
int m = 0; // array length of fullArray
char redactString[] = "the, jumps, lazy";
char **redactArray = NULL; // tokenized array for redactString
int n = 0; // array length of redactArray
char *token;
int i, j, k;
for (token = strtok(fullSentence, " "); token != NULL; token = strtok(NULL, " ")) {
fullArray = realloc(fullArray, (m 1) * sizeof(*fullArray));
fullArray[m] = malloc(strlen(token) 1);
strncpy(fullArray[m], token, strlen(token) 1);
m ;
}
for (token = strtok(redactString, ", "); token != NULL; token = strtok(NULL, ", ")) {
redactArray = realloc(redactArray, (n 1) * sizeof(*redactArray));
redactArray[n] = malloc(strlen(token) 1);
strncpy(redactArray[n], token, strlen(token) 1);
n ;
}
// compare the words one by one ignoring case
for (i = 0; i < m; i ) {
for (j = 0; j < n; j ) {
if (strcasecmp(fullArray[i], redactArray[j]) == 0) {
// the words match. redact the word in fullArray[i]
for (k = 0; k < strlen(fullArray[i]); k ) {
fullArray[i][k] = '*';
}
}
}
}
// print the redacted string
for (i = 0; i < m; i ) {
printf("%s%s", fullArray[i], i == m - 1 ? "\n" : " ");
}
return 0;
}
Output:
*** quick brown fox ***** over *** **** dog