SlideShare a Scribd company logo
The Task
For this assignment you will write a rudimentary text editor that allows the user to edit 5 lines of
text, where each line is no longer than 80 characters. The editor should allow the user to
continue editing as long as desired and should print the current state of the edit buffer after each
edit.
The editor is a 'line editor' in that the user must edit one line at a time. The user can specify
which line should be edited by choosing a line number from a menu.
The only two editing operations possible are to replace an entire line with a new line, or to
replace a substring in the line with a new substring.
Musts
The program should not accept incorrect menu choices from the user. If the user creates a string
that is longer than 80 characters the string should be truncated to fit the 80 character limit. The
program should simply make no changes if the user tries to replace a substring that does not exist
in the string.
Your program must use functions. Some functions are required, but you may make other
functions as you see fit. You may not change the name, return type, or the parameter list types
for required functions.
Required Function One
int replaceInString(char[] original, char[] substring, char[] replace);
This function causes the original string to be modified such that the first occurrence of substring
is removed from the original string and the contents of replace are inserted in its place.
replaceInString calls findSubString and insertString. The function returns 0 if the operation
fails and 1 if the operation is successful.
Required Function Two:
int findSubString(char[] original, char[] toFind);
This function finds the first occurrence of toFind in original and returns an integer representing
the index of the first element of the toFind substring in original. For example if toFind was 'cat'
and original was 'thundercat' the function would return 7 since the begining of 'cat' in
'thundercat' is position 7. If the function does not find a substring it should return -1
note: do not use existing substring functions such as strstr as a solution for this function. Solve
the algorithm yourself. You may use basic string functions such as strlen and strcat.
Required Function Three:
int insertString(char[] original, int start, int length, char[] toInsert);
This function replaces the contents of original with the following sequence of characters:
the characters from original up to position start-
the characters from toInsert
the characters from original starting at the character immediately after length.
Solution
#include
#include
#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] = '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 = '0';
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] = '0';
} 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 = '0';
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] = '0';
//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] = '0';
}
}

More Related Content

PPTX
POEPPSGNHwkejnkweoewnkenjwjewkjewoewkjewijewjk
PDF
In C++Add the function min as an abstract function to the classar.pdf
ODP
PHP Web Programming
PPT
PDF
READ BEFORE YOU START Please read the given Word document fo.pdf
PDF
you will implement some sorting algorithms for arrays and linked lis.pdf
PPTX
C++ Programming Homework Help
POEPPSGNHwkejnkweoewnkenjwjewkjewoewkjewijewjk
In C++Add the function min as an abstract function to the classar.pdf
PHP Web Programming
READ BEFORE YOU START Please read the given Word document fo.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
C++ Programming Homework Help

Similar to The Task For this assignment you will write a rudimentary text edi.pdf (20)

DOCX
#include string.h#include stdlib.h#include systypes.h.docx
DOCX
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
PDF
[ITP - Lecture 17] Strings in C/C++
PDF
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
PDF
Note Modified codecode#includeiostream #include stdio.h.pdf
PPTX
Diploma ii cfpc u-4 function, storage class and array and strings
DOCX
Unitii string
PDF
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
PPTX
Lecture 15_Strings and Dynamic Memory Allocation.pptx
DOCX
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
PDF
helpInstructionsAdd the function max as an abstract function to .pdf
PPTX
Dti2143 chapter 5
PDF
Write a program that converts an infix expression into an equivalent.pdf
PDF
For this homework, you will write a program to create and manipulate.pdf
DOC
Assignment c programming
PPT
Unit 4
PPT
M C6java7
DOCX
ObjectivesMore practice with recursion.Practice writing some tem.docx
PDF
Given an expression string exp, write a java class ExpressionCheccke.pdf
PPTX
unit-5 String Math Date Time AI presentation
#include string.h#include stdlib.h#include systypes.h.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
[ITP - Lecture 17] Strings in C/C++
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Note Modified codecode#includeiostream #include stdio.h.pdf
Diploma ii cfpc u-4 function, storage class and array and strings
Unitii string
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
Lecture 15_Strings and Dynamic Memory Allocation.pptx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
helpInstructionsAdd the function max as an abstract function to .pdf
Dti2143 chapter 5
Write a program that converts an infix expression into an equivalent.pdf
For this homework, you will write a program to create and manipulate.pdf
Assignment c programming
Unit 4
M C6java7
ObjectivesMore practice with recursion.Practice writing some tem.docx
Given an expression string exp, write a java class ExpressionCheccke.pdf
unit-5 String Math Date Time AI presentation
Ad

More from info785431 (20)

PDF
Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
PDF
Compare and contrast the messages about science and integrity in Fra.pdf
PDF
Briely, what was Darwins explanation for the appearance of design.pdf
PDF
A router receives a message addressed 172.16.15.75. The relevant rou.pdf
PDF
A study of sandflies in Panama classified flies caught in light traps.pdf
PDF
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
PDF
You have been exposed to each of the 8 microbes below. One of them h.pdf
PDF
Write a snippet of C code that will enable the ADC to continuously r.pdf
PDF
Write a JAVA LinkedListRec class that has the following methods siz.pdf
PDF
Write a BFS algorithm using only arrays and no other data structure..pdf
PDF
Why has one prominent textbook author described IO management as the.pdf
PDF
which is true of the data shown in the histogram Which is true of th.pdf
PDF
What is the value of studying humanities in a business or technical .pdf
PDF
What are the two components of dynamic pressureVelocity and densi.pdf
PDF
USING JAVAImplement the quicksort optimization median-of-three, i.pdf
PDF
There are 40 students in our class. How many ways they can be lined .pdf
PDF
The SIP handles what functionsA.) establishes a call through the .pdf
PDF
The NBA decides to look into the use of meldonium in the league foll.pdf
PDF
The organelle that serves as the digestive system in the cell is the .pdf
PDF
The major type of interactive forces between molecules of NH_3 are .pdf
Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
Compare and contrast the messages about science and integrity in Fra.pdf
Briely, what was Darwins explanation for the appearance of design.pdf
A router receives a message addressed 172.16.15.75. The relevant rou.pdf
A study of sandflies in Panama classified flies caught in light traps.pdf
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
You have been exposed to each of the 8 microbes below. One of them h.pdf
Write a snippet of C code that will enable the ADC to continuously r.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a BFS algorithm using only arrays and no other data structure..pdf
Why has one prominent textbook author described IO management as the.pdf
which is true of the data shown in the histogram Which is true of th.pdf
What is the value of studying humanities in a business or technical .pdf
What are the two components of dynamic pressureVelocity and densi.pdf
USING JAVAImplement the quicksort optimization median-of-three, i.pdf
There are 40 students in our class. How many ways they can be lined .pdf
The SIP handles what functionsA.) establishes a call through the .pdf
The NBA decides to look into the use of meldonium in the league foll.pdf
The organelle that serves as the digestive system in the cell is the .pdf
The major type of interactive forces between molecules of NH_3 are .pdf
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Lesson notes of climatology university.
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Complications of Minimal Access Surgery at WLH
PDF
Classroom Observation Tools for Teachers
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Insiders guide to clinical Medicine.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
master seminar digital applications in india
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Computing-Curriculum for Schools in Ghana
PPTX
GDM (1) (1).pptx small presentation for students
human mycosis Human fungal infections are called human mycosis..pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
Microbial diseases, their pathogenesis and prophylaxis
Lesson notes of climatology university.
Anesthesia in Laparoscopic Surgery in India
Complications of Minimal Access Surgery at WLH
Classroom Observation Tools for Teachers
O7-L3 Supply Chain Operations - ICLT Program
Module 4: Burden of Disease Tutorial Slides S2 2025
Abdominal Access Techniques with Prof. Dr. R K Mishra
Insiders guide to clinical Medicine.pdf
VCE English Exam - Section C Student Revision Booklet
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
master seminar digital applications in india
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Supply Chain Operations Speaking Notes -ICLT Program
Computing-Curriculum for Schools in Ghana
GDM (1) (1).pptx small presentation for students

The Task For this assignment you will write a rudimentary text edi.pdf

  • 1. The Task For this assignment you will write a rudimentary text editor that allows the user to edit 5 lines of text, where each line is no longer than 80 characters. The editor should allow the user to continue editing as long as desired and should print the current state of the edit buffer after each edit. The editor is a 'line editor' in that the user must edit one line at a time. The user can specify which line should be edited by choosing a line number from a menu. The only two editing operations possible are to replace an entire line with a new line, or to replace a substring in the line with a new substring. Musts The program should not accept incorrect menu choices from the user. If the user creates a string that is longer than 80 characters the string should be truncated to fit the 80 character limit. The program should simply make no changes if the user tries to replace a substring that does not exist in the string. Your program must use functions. Some functions are required, but you may make other functions as you see fit. You may not change the name, return type, or the parameter list types for required functions. Required Function One int replaceInString(char[] original, char[] substring, char[] replace); This function causes the original string to be modified such that the first occurrence of substring is removed from the original string and the contents of replace are inserted in its place. replaceInString calls findSubString and insertString. The function returns 0 if the operation fails and 1 if the operation is successful. Required Function Two: int findSubString(char[] original, char[] toFind); This function finds the first occurrence of toFind in original and returns an integer representing the index of the first element of the toFind substring in original. For example if toFind was 'cat' and original was 'thundercat' the function would return 7 since the begining of 'cat' in 'thundercat' is position 7. If the function does not find a substring it should return -1 note: do not use existing substring functions such as strstr as a solution for this function. Solve the algorithm yourself. You may use basic string functions such as strlen and strcat. Required Function Three: int insertString(char[] original, int start, int length, char[] toInsert); This function replaces the contents of original with the following sequence of characters:
  • 2. the characters from original up to position start- the characters from toInsert the characters from original starting at the character immediately after length. Solution #include #include #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] = '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 {
  • 3. printf("File read unsuccessful "); } } //continue asking for input until the user chooses to quit char userInput = '0'; 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();
  • 4. //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: ");
  • 5. 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
  • 6. 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[]) {
  • 7. //remove the new line at the end if (line[strlen(line) - 1] == ' ') { line[strlen(line) - 1] = '0'; } 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 = '0'; 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
  • 8. 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
  • 9. */ 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;
  • 10. } //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] = '0'; //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] = '0'; } }