Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB Bleep out the given \"censored\" substring in an original text string, ig

ID: 3148038 • Letter: M

Question

MATLAB

Bleep out the given "censored" substring in an original text string, ignoring case. For ead censored substring found, replace every character with … except for the first charact For example: if "fish" is a censored substring, the original text Fish' becomes 'F* t takes two input strings. 1st the original text string to be searched on, 2nd-the censored substring, and returns the censored text string. You may assume there will not be complication from unusual censored substring like 'sss', or 'haha' vs. original text of 'ssssssss hahahahaha'. To keep the problem simple, the result will be compared, ignoring case. For exampl suppose 'F*isexpected. The string '*will also be considered correct. If you want to challenge yourself, try to preserve uppercase/lowercase of th first characters of the censored substrings o Do not attempt the challenge until finish all other problems. Examples: >> orig-text = 'Fishermen Eished a ticklish swordfER. #FiSHiNg !'; censored text censoredtext= censorsubstr (origtext, 'FISH') - - - F ermen f ed a ticklish swordf ing ! . Hints This problem is similar to Problem 1, but it has some complications

Explanation / Answer


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

#define ROW_LENTH 81
#define NUM_ROWS 5

void replaceLine(char line[]);
void printText(char text[][ROW_LENTH]);

int readFile(char filePath[], char text[][ROW_LENTH]);
int writeFile(char filePath[], char text[][ROW_LENTH]);
void removeTrailingHardReturn(char line[]);
void flushBuffer();
int getLine();

int replaceInString(char original[], char substring[], char replace[]);
int findSubString(char original[], char toFind[]);
void insertString(char original[], int start, int length, char toInsert[]);


int main(int argc, char *argv[]) {
   //make the text buffer and zero it
   char text[NUM_ROWS][ROW_LENTH];
   for (int i = 0; i < NUM_ROWS; i++) {
      text[i][0] = '';
   }
   //check for file path arguments
   if (argc == 2) {
      printf("File argument detected. Reading file... ");
      //read the file
      if (readFile(argv[1], text)) {
         printf("File read successfully ");
      } else {
         printf("File read unsuccessful ");
      }
   }

   //continue asking for input until the user chooses to quit
   char userInput = '';
   while(userInput != 'q') {
      //print out the text buffer
      printText(text);
      //ask for and get input
      printf("Enter q to quit, r to replace a line, i to insert a substring over another ");
      userInput = getchar();

      switch (userInput) {
         //if they want to quit
         case 'q':
            printf("You have chosen to quit. Goodbye! ");
            //save the text buffer back to the file
            if (argc == 2) {
               printf("Changes will now be saved to file ");
               if (writeFile(argv[1], text)) {
                  printf("File written successfully ");
               } else {
                  printf("Error writing file ");
               }
            }
            break;

         //if they want to replace an entire line
         case 'r':
            //get the line
            replaceLine(text[getLine()]);
            break;

         case 'i':
            //must have an empty statement because a variable cannot be
            //declared as part of the same statement as a label
            ;
            int lineNum = getLine();
            //print that one line
            printf("Line %c looks like: %s ", lineNum, text[lineNum]);
            //get the substring to replace
            char toReplace[ROW_LENTH];
            printf("Please enter the subSring to replace in the line: ");
            flushBuffer();
            fgets(toReplace, ROW_LENTH, stdin);
            removeTrailingHardReturn(toReplace);

            //get the substring to replace with
            char replaceWith[ROW_LENTH];
            printf("Please enter the subSring to replace the old subString with: ");
            fgets(replaceWith, ROW_LENTH, stdin);
            removeTrailingHardReturn(replaceWith);
          
            //do the replacement
            if (replaceInString(text[lineNum], toReplace, replaceWith)) {
               printf("Replacement successful! ");
            } else {
               printf("Replacement unsuccessful! ");
            }
            break;

         default:
            printf("Invalid input. Please try again ");
            break;
      }
   }
   return 0;
}

/*
This function overwrites one of the lines in the text
PARAMS:
line, a char array containing the line to overwrite
*/
void replaceLine(char line[]) {
   flushBuffer();
   printf("Please enter the text to replace the line with: ");
   fgets(line, ROW_LENTH, stdin);
   removeTrailingHardReturn(line);
}

/*
This function prints the all 5 lines for the user to see
PARAMS:
text, a 2D char array containing all 5 lines of the text
*/
void printText(char text[][ROW_LENTH]) {
   //print all 5 lines
   printf("The text currently looks like: ");
   for (int i = 0; i < NUM_ROWS; i++) {
      if (strlen(text[i]) == 0) {
         printf("*LINE EMPTY* ");
      } else {
         printf("%s ", text[i]);
      }
   }
}

/*
This function reads lines of text from a file and puts them into the text array
PARAMS:
filePath, a string containing the path to the file with the data
text, a 2D char array containing all 5 lines of the text
*/
int readFile(char filePath[], char text[][ROW_LENTH]) {
   //open the file
   FILE* inFile = fopen(filePath, "r");
   //check to see if the file exists
   if (inFile != NULL) {
      //read 5 lines or until end of file
      for (int i = 0; i < 5 && !feof(inFile); i++) {
         fscanf(inFile, "%s", text[i]);
         removeTrailingHardReturn(text[i]);
      }
      //close file
      fclose(inFile);
      return 1;
   } else {
      //close file, return fail
      fclose(inFile);
      return 0;
   }
}

/*
This function writes the user's text to a file
PARAMS:
filePath, a string containing the path to the file with the data
text, a 2D char array containing all 5 lines of the text
*/
int writeFile(char filePath[], char text[][ROW_LENTH]) {
   //open the file
   FILE* outFile = fopen(filePath, "w");
   //check that it worked
   if (outFile == NULL) {
      return 0;
   }else {
      //write all 5 lines
      for (int i = 0; i < 5; i++) {
         fprintf(outFile, "%s ", text[i]);
      }
      //close and return
      fclose(outFile);
      return 1;
   }
}

/*
This function removes the newline character from the end of a string
PARAMS:
line, a char array containing the line remove the hard return from
*/
void removeTrailingHardReturn(char line[]) {
   //remove the new line at the end
   if (line[strlen(line) - 1] == ' ') {
      line[strlen(line) - 1] = '';
   } else {
      //if there was no newline, then flush the buffer because it's still in there
      flushBuffer();
   }
}

/*
This function removes everything from the input stream buffer so that
there is no erratic input to my menus from truncated input,
also removes the newlines from the end of input
*/
void flushBuffer() {
   char input = '';
   do {
      input = getchar();
   } while (input != ' ' && input != EOF);
}

/*
This finction gets an integer input from 1 to the number of rows.
RETURNS
An integer from 1-5 (inclusive)
*/
int getLine() {
   int validLine = 0;
   int lineNum = -1;
   //loop until the user input is valid
   while (!validLine){
      //ask for and get 1 character of input
      printf("Please enter a line number to replace (1-5) ");
      flushBuffer();
      lineNum = getchar();
      //check that it is a number between 1 and the number of rows (inclusive)
      if (lineNum >= '1' && lineNum <= NUM_ROWS + 49) {
         //if it is, return
         return (int) lineNum - 49;
      } else {
         printf("Invalid input. Please try again. ");
      }
   }
   return -1;
}

/*
This function utilizes findsubstring and insertstring to overwrite a substring
in a string with another
PARAMS
original, a character array that has the string that is to be changed
subString, a character array that contains the substring in original to be replaced
replace, a character array to replace the subString in original with
RETURNS
1 if successful (substring was found and replaced), 0 otherwise
*/
int replaceInString(char original[], char substring[], char replace[]) {
   //find the location of the substring
   int location = findSubString(original, substring);
   //check to see if the substring is in the original string
   if (location == -1) {
      return 0;
   } else {
      //insert the string an return depending on success
      insertString(original, location, strlen(substring), replace);
         return 1;
   }
}

/*
This function finds the first occurance of a substring in a string
PARAMS:
original, a char array of the string to search for the substring
toFind, a char array with the substring to search for
RETURNS
the index of the first character in the substring, or -1 if the substring was not found
*/
int findSubString(char original[], char toFind[]) {
   //loop through the string
   for (int i = 0; i < strlen(original); i++) {
      //if it matches the first character begin looping through the substring
      if (original[i] == toFind[0]) {
         short match = 1;
         //check that the following characters match the substring
         for (int j = 1; j < strlen(toFind); j++) {
            if (original[i + j] != toFind[j]) {
               match = 0;
               break;
            }
         }
         //if they all match, return the location
         if (match) {
            return i;
         }
      }
   }
   return -1;
}

/*
This function inserts a string into another, overwriting part of that string
PARAMS:
original, a char array of the string to be changed
start, the index at which to insert the first character of the substring ebing inserted
length, the length of the original to be overwritten
toInsert, the substring to insert into the original string
RETURNS
1 if successful, 0 if not successful
*/
void insertString(char original[], int start, int length, char toInsert[]) {
   if (start < 0 || length < 0) {
      printf("Invalid parameter, no changes made ");
      return;
   }
   //create a copy of the original string
   char originalCopy[ROW_LENTH];
   strcpy(originalCopy, original);
   //end the string where the inserting string will start
   original[start] = '';
   //add the inserted string
   strcat(original, toInsert);
   //add the end of the original string back to the end of the new string
   for (int i = start + length; i < strlen(originalCopy); i++) {
      int len = strlen(original);
      original[len] = originalCopy[i];
      original[len + 1] = '';
   }
}