C Program using UNIX. Write a program to replace an ordinary plain text into an
ID: 3913080 • Letter: C
Question
C Program using UNIX.
Write a program to replace an ordinary plain text into an unintelligible gibberish text. A key is used for replacement of alphabetic letters. Write the program with 26 elements of the key shown below:
char key[27] = "mkrewyugptiaqdfhlnvosbzcxj";
The letter ‘a’ is replaced by the letter ‘m’, ‘b’ by ‘k’, ‘c’ by ‘r’, and so on.
Example input/output Input: A mystery
Out: M qxvownx
Your program should include the following function:
void replace(char *s1, char *s2);
The function expects s1 to point to a string containing the input as a string and stores the output to the string pointed by s2. Hint: use the distance between a character and ‘a’ or ‘A’ as the index for the characters in the key string. For example, the character ‘a’ is replaced by ‘m’, which is at the index 0 in the key, ‘a’ –‘a’ = 0, index for ‘b’ is 1, etc.
1) Name your program replace_text.c.
2) The input string may contain any character (upper case, lower case, punctuation, etc.). Upper case letters should remain upper case after replacement and lower case remain lower case. Punctuations and white spaces should remain unchanged.
3) The replace function should use pointer arithmetic (instead of array subscripting) to visit input string s1 and output string s2.
4) In the main function, declare the string variables for input and output. Read a line of text, and then call the replace function. The main function should display the output.
5) To read a line of text, use the read_line function (the pointer version) in the lecture notes.
Explanation / Answer
You have not given the read_line function so I have used a getline() function(inbuilt command). But I suppose you can easily replace the getline() function that I have used in the code with the read_line() function in your lecture notes without any difficulty.
Working Code in C:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
void replace(char *s1, char *s2);
int main(){
// printf("%s ",key);
size_t x_sz = 0;
char *s1 = 0;
int x_len = getline(&s1, &x_sz, stdin);
printf("s1:%s ", s1);
int l = strlen(s1);
char* s2 = (char*) malloc((l + 1) * sizeof(char));
replace(s1,s2);
printf("s2:%s ", s2);
}
void replace(char *s1, char *s2){
char key[27] = "mkrewyugptiaqdfhlnvosbzcxj";
int l = strlen(s1);
int i=0;
for (i = 0 ; i < l ; i++) {
if(*(s1+i)>='A' && *(s1+i)<='Z'){
int position = *(s1+i)-'A';
*(s2+i) = 'A'+(key[position]-'a');
}
else if(*(s1+i)>='a' && *(s1+i)<='z'){
int position = *(s1+i)-'a';
*(s2+i) = key[position];
}
else{
*(s2+i) = *(s1+i);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.