Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace\remove character in string

Tags:

c++

string

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?

like image 450
Cornwell Avatar asked Oct 07 '10 13:10

Cornwell


People also ask

How do I remove a specific character from a string?

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.

How do I remove a character from a string in Java?

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.

How do you replace a character in a string in Python?

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.


1 Answers

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(), '/', '-');
like image 57
Fred Foo Avatar answered Sep 24 '22 01:09

Fred Foo