In C: Using pointers and avoiding unnecessary local variable, write a function,
ID: 3821336 • Letter: I
Question
In C: Using pointers and avoiding unnecessary local variable, write a function, rmchr, that takes a string and a character as arguments, removing all occurrences of the character from the string(watch out for sequential occurrences of the character). Rmch should not leave holes in the string. What should rmchr return? It shouldn’t return anything.
Print the string both before and after your call to rmchr to demonstrate that the original string was modified.
The code should look something like the stuff below:
char s1[]= “abracadabra”;
char s2[]= “abracadabra”;
char s3[]= “abracadabra”;
char s4[]= "aaaa"
char s5= "aaaa"
printf(“%s ”,s1);
rmchr(s1, ‘a’);
printf(“%s , s1”);
Run your program using the following strings and characters:
string character answer
"abracadabra" 'a' brcdbr
"abracadabra" 'b' aracadara
"abracadabra" 'n' abracadabra
"aaaa" 'a' print nothing
"aaaa" 'n' aaaa
Make the code follow the below information:
1. comments on the following:
- program description
- function descriptions
- all variable and constant declarations
- ambiguous or complex sections of code
2. the correct use of local variables, local prototypes, and parameter passing
Explanation / Answer
//Header Files
#include<stdio.h>
#include<string.h>
//Function Declaration String,Character passing into function
void rmchr(char[],char);
int main(){
//Declaration of String variables
char s1[]= "abracadabra";
char s2[]= "abracadabra";
char s3[]= "abracadabra";
char s4[]= "aaaa";
char s5[]= "aaaa";
printf("STRING CHARACTER ANSWER ");
printf("%s ",s1); //Printing String Before Passing
rmchr(s1,'a'); //Passing String and Character to remove into rmchr function
printf("%s ",s2);//Printing String Before Passing
rmchr(s2,'b');//Passing String and Character to remove into rmchr function
printf("%s ",s3);//Printing String Before Passing
rmchr(s3,'n');//Passing String and Character to remove into rmchr function
printf("%s ",s4);//Printing String Before Passing
rmchr(s4,'a');//Passing String and Character to remove into rmchr function
printf("%s ",s5);//Printing String Before Passing
rmchr(s5,'n');//Passing String and Character to remove into rmchr function
return 0;
}
//Function Definition
void rmchr(char str[],char ch){
char *p;//Pointer Variable
p=&str[0]; //Storing address of First character of String in *p
printf("%c ",ch); // Printing Character to remove
while(*p!=''){ //Loop for iterating String
if(*p!=ch){ // Checking if Character is not equal to each character
printf("%c",*p); //Prints that unequal character
}
p++; //Address Increment of *p
}
printf(" ");
}
//Output:
STRING CHARACTER ANSWER
abracadabra a brcdbr
abracadabra b aracadara
abracadabra n abracadabra
aaaa a
aaaa n aaaa