string DelStr = "I! am! bored!";
string RepStr = "10/07/10"
I want to delete all '!' on DelStr and I want to replace all '/' with '-' on the RepStr string.
Is there any way to do this without doing a loop to go through each character?
You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement.
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
Remove the exclamations:
#include <algorithm>
#include <iterator>
std::string result;
std::remove_copy(delStr.begin(), delStr.end(), std::back_inserter(result), '!');
Alternatively, if you want to print the string, you don't need the result
variable:
#include <iostream>
std::remove_copy(delStr.begin(), delStr.end(),
std::ostream_iterator<char>(std::cout), '!');
Replace slashes with dashes:
std::replace(repStr.begin(), repStr.end(), '/', '-');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With