Using pointers write a function called removeChar that will remove each instance
ID: 3871465 • Letter: U
Question
Using pointers write a function called removeChar that will remove each instance of a specified character from a CString.
A CString is defined as an array of characters that is terminated by the NULL ('') character.
Your function should return the number of characters that were removed from the string.
Your function should take as arguments, the CString to remove the characters from, and the character to remove.
Note:
The argument which represents the character to be removed should be a default argument. Meaning that if a character is not provided it will default to the space character (Decimal 32 or Hex 20).
Using the subscript operator [] is not using a pointer.
What not to do
Using any of the following will drop your grade for this assignment by 70%
global variables.
cin in any funciton other than main
cout in any funciton other than main
goto statements
Note:
To get a sentence from the keyboard you must use cin.getline:
char str[100];
cin.getline(str, 99); // save room for the null character.
Your output should look something like the following:
C:Windows system32cmd.exe This is a test i hope it works Enter a character to remove Removed 4 i characters. Your string is now: Ths s a test hope t works Press any key to continue - - -Explanation / Answer
#include<iostream>
using namespace std;
int removeChar(char* str, char c) //pass the pointer to the CString an the character to remove
{
char *pr = str, *pw = str; //initialise 2 pointers to the array
int co=0; //initialise count variable to 0
while (*pr) //check until end of the CString
{
/*the idea here is to keep a seperate reading pointer and a seperate writing pointer.
you advance the reading pointer always and the writing pointer only if it is not pointing to the character given*/
*pw = *pr++; //pr is reading pointer, pw is writing pointer
if(*pw!=c) //if not pointing to the character
{
pw += (*pw != c); //write it to writing pointer
}
else //if pointing to character, do not write it
co++; //increment count of removed characters, or characters we are not writing
}
*pw = ''; //terminate the string
return co; //return the count
}
int main() {
char str[100] ,ch;
int no;
cout<<"Enter a string: ";
cin.getline(str,99); //input the string
cout<<"Enter the character to remove : ";
cin>>ch; //input the character to remove
if(ch) //if character is inputted
{
no=removeChar(str,ch); //find no of occurences and new string
}
else //if character is not inputted
no=removeChar(str, ' '); //find no of occurences of ' ' and remove ' '
printf(" Removed %d %c characters. Your string is now : %s ", no,ch,str); //print the removed character, occurence and new string
return 0;
}
For this input :
We get this output :
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.