5. Write a function named deleteG that accepts one character pointer as a parame
ID: 3748899 • Letter: 5
Question
5. Write a function named deleteG that accepts one character pointer as a parameter and returns no value. The parameter is a C string. This function must remove all of the upper and lower case 'g' letters from the string. The resulting string must be a valid C string. Your function must declare no more than one local variable in addition to the parameter, that additional variable must be of a pointer type. Your function must not use any square brackets and must not use the strlen or strcpy library functions int main() char msg [100] = "I recall the glass gate next to Gus in Lagos, near the gold bridge." deleteG (msg) coutExplanation / Answer
The solution given does not really meet the specification in the question. The question says use only one more extra variable other than the parameter passed to the function. I have given a better solution and the comments before the function explains how it works. I hope you would be able to follow.
Please do rate the answer if it helped. Thank you
#include <iostream>
using namespace std;
void deleteG(char *msg);
int main(){
char msg[100] = "I recall the glass gate next to Gus in Lagos near the gold bridge.";
cout << "Original message is: " << msg << endl;
deleteG(msg);
cout << "Modified message is: " << msg << endl;
}
// remove all lower and upper case G.
//uses a pointer initially pointing to start of the string. Initially both msg and ptr point to start
// of input msg. msg pointer is used to scan the input characters, whereas ptr will be used to remember
//address where to overwrite characters. The input string itself is modified by moving chars.
//As we scan the input characters in the given msg, we check if it is 'g' or 'G' .
//---->if the current scanned char is 'g' or 'G' then we skip copying the char and only increment msg
//---->if the current char is non-G then we copy over the char to address pointed by ptr and move both ptr and msg
//this is repeated till we have processed all chars
void deleteG(char *msg){
char *ptr = msg;
while(*msg != ''){
if(*msg == 'g' || *msg == 'G') //need to delete?, then don't copy
{
msg++;
}
else
{
*ptr = *msg; //copy the current char to address where some old char will be overwritten
//increment both pointers
ptr++;
msg++;
}
}
*ptr = ''; //put terminating null character
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.