In: Computer Science
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements
1. Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise
2. Replace "sh" with ph
This is the text to be manipulated:
Paragraph1
She told us to take the trash out.
Why did she do that?
I wish she would not do that
Paragraph 2
We came home very late despite the fact we had school the next day.
We had a lot of fun
I miss my friends.
In c programming language please
C code that reads a text file, create a linked list of characters from file then replaces characters as per instructions.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct node {
char val;
struct node * next;
} node_t;
void print_list(node_t * head) {
node_t * current = head;
while (current != NULL) {
printf("%c", current->val);
current = current->next;
}
}
void push_back(node_t * head, char val) {
node_t * current = head;
while (current->next != NULL) {
current = current->next;
}
/* now we can add a new variable */
current->next = (node_t *) malloc(sizeof(node_t));
current->next->val = val;
current->next->next = NULL;
}
void replace_chars(node_t* head) {
node_t* current = head;
node_t* prev = head;
if (head != NULL) {
prev = current;
current = current->next;
while (current != NULL) {
if (tolower(current->val) == 's' || tolower(current->val) == 'e' || tolower(current->val) == 'y') {
if (tolower(prev->val) == 'c') prev->val = (char)((int)prev->val + 16);
}
if (tolower(current->val) == 'h' && tolower(prev->val) == 's') prev->val = (char)((int)prev->val - 3);
prev = current;
current = current->next;
}
}
}
int main() {
// open file
FILE *fp;
fp = fopen("test.txt", "r");
// crate head of linked list
node_t * head = NULL;
head = (node_t *) malloc(sizeof(node_t));
// reads single character from file
char c = fgetc(fp);
head->val = c;
// run this while loop till we reach EOF (end of file)
while (c != EOF) {
// read a character
c = fgetc(fp);
// add latest character to end of linked list
if (c != EOF) push_back(head, c);
}
replace_chars(head);
print_list(head);
return 0;
}
File - test.txt
Output:
Please refer this screenshot for indentation help:
If you need any help, please leave a comment. If you are happy with my answer, please consider giving a like.