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 updated string.
Test Data:
("Filename", "e") -> "Filnam"
("Compilation Time", "i") -> "Complaton Tme"
Sample Solution:
C++ Code:
#include <bits/stdc++.h> // Include all standard libraries
using namespace std; // Using the standard namespace
// Function to remove all occurrences of a specific character from a string
string test(string str, char ch) {
std::string result_str; // Initialize an empty string to store the modified string
result_str.reserve(str.size()); // Reserve memory to optimize string appending
for (size_t i = 0; i < str.size(); ++i) { // Loop through each character in the input string
if (str[i] != ch) { // Check if the character is not equal to the specified character
result_str += str[i]; // Append the character to the result string if it's different from 'ch'
}
}
return result_str; // Return the modified string after removing occurrences of 'ch'
}
int main() {
// Test cases
string str = "Filename"; // Define a string
char ch = 'e'; // Define a character
cout << "String: " << str;
cout << "\nCharacter: " << ch;
cout << "\nRemove '" << ch << "' from '" << str << "': " << test(str, ch) << endl; // Display the string after removing 'e' from "Filename"
str = "Compilation Time"; // Update the string
ch = 'i'; // Update the character
cout << "\nString: " << str;
cout << "\nCharacter: " << ch;
cout << "\nRemove '" << ch << "' from '" << str << "': " << test(str, ch) << endl; // Display the string after removing 'i' from "Compilation Time"
}
Sample Output:
String: Filename Character: e Remove 'e' from 'Filename': Filnam String: Compilation Time Character: i Remove 'i' from 'Compilation Time': Complaton Tme
Flowchart:
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/string/cpp-string-exercise-38.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics