Write a C++ program for function of removeChar that removes all the occurrences
ID: 3683625 • Letter: W
Question
Write a C++ program for function of removeChar that removes all the occurrences of a character in a string. For example, given a string of “ab cd 1 2” and a whitespace character, the string becomes “abcd12”. You can assume that the string can be modified.
1. In the main function, ask the user to enter a string and a character to be removed.
2. The entered string should be handled as a C-string (or is converted to a C-string).
3. Write a removeChar function that takes a pointer parameter (char *) and a char parameter.
4. In the main function, print out the original string and the string with the character being removed.
5. The removeChar function should be implemented using the pointer notation only.
** Do not use library functions except strlen() to get the length of a string and cin.get() to take a whitespace character from the keyboard.
Explanation / Answer
#include <iostream>
#include <cstring>
using namespace std;
void removeChar( char* str, char ch)
{
int i,j;
int len = strlen(str);
for(i=0;i<len;i++)
{
if(str[i]==ch)
{
for(j=i;j<=len;j++)
*(str + j) = *(str + j+1);
}
}
}
int main()
{
char orig[100];
char ch;
int i=0;
cout<<"Enter a string: ";
cin.get(ch);
while(ch!=' ')
{
orig[i++] = ch;
cin.get(ch);
}
orig[i] = '';
cout<<" Enter a character: ";
cin.get(ch);
printf("String before removal of occurence of character %s", orig);
removeChar(orig, ch);
printf(" String after removal of occurence of character %s ", orig);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.