w3resource

C++ String Exercises: Remove a specific character from a given string

C++ String: Exercise-38 with Solution

Write a C++ program that removes a specific character from a given string. Return the new string.

Test Data:
("Filename", "e") -> "Filnam"
("Compilation Time", "i") -> "Complaton Tme"

Sample Solution:

C++ Code:

#include <bits/stdc++.h>

using namespace std;
string test(string str, char ch)
{
std::string result_str;
result_str.reserve(str.size());
for(size_t i = 0; i < str.size(); ++i)
  {
   if(str[i] != ch) 
     result_str += str[i];
  }
  return result_str;
}

int main()
{
	string str = "Filename";
	char ch ='e';
	cout << "String: " << str;
	cout << "\nCharacter: " << ch;
	cout << "\nRemove '" << ch << "' from '" << str << "': " << test(str, ch) << endl; 
	str = "Compilation Time";
	ch ='i';
	cout << "\nString: " << str;
	cout << "\nCharacter: " << ch;
	cout << "\nRemove '" << ch << "' from '" << str << "': " << test(str, ch) << endl; 
}

Sample Output:

String: Filename
Character: e
Remove 'e' from 'Filename': Filnam

String: Compilation Time
Character: i
Remove 'i' from 'Compilation Time': Complaton Tme

Flowchart:

Flowchart: Remove a specific character from a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Count occurrences of a certain character in a string.

Next C++ Exercise: Find Unique Character String.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x