C++ Program to Remove Specific Character from the String

This C++ Program which removes a given character from the string. The program takes a string and the character to be removed as the input, uses standard library remove( ) algorithm for returning a range of elements with all the elements equal to the character removed which when passed to the standard library algorithm erase( ) erases the character from the entire string.

Here is source code of the C++ program which removes a given character from the string. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Remove given Character from the String
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <algorithm>
  7.  
  8. int main()
  9. {
  10.     std::string s;
  11.     char c;
  12.  
  13.     std::cout << "Enter the string : ";
  14.     std::cin >> s;
  15.     std::cout << "\nEnter the character : ";
  16.     std::cin >> c;
  17.     /* Removing character c from s */
  18.     s.erase(std::remove(s.begin(), s.end(), c), s.end());
  19.     std::cout << "\nString after removing the character "
  20.               << c << " : " << s;
  21. }

$ g++ main.cpp
$ ./a.out
Enter the string : Mediterranzean
Enter the character : z
String after removing the character z : Mediterranean

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.