8

How to replace one char by another using std::string in C++? In my case, I'm trying to replace each c character by character.

I've tried this way :

std::string str = "abcccccd";
str = str.replace('c', ' ');

But, this wouldn't work.

Lucie kulza
  • 1,357
  • 6
  • 20
  • 31
  • 1
    A few seconds of searching [came up with this](http://stackoverflow.com/a/12152291/1322972). – WhozCraig Mar 14 '14 at 10:38
  • possible duplicate of [How to find and replace all characters in a string with specific symbols C++](http://stackoverflow.com/questions/19546367/how-to-find-and-replace-all-characters-in-a-string-with-specific-symbols-c) – juanchopanza Mar 14 '14 at 10:40
  • Possible duplicate of [How to replace all occurrences of a character in string?](https://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string) – phuclv Aug 03 '18 at 05:14

1 Answers1

14

With the std::replace algorithm:

#include <algorithm>
#include <string>
#include <iostream>

int main()
{
  std::string str = "abccccd";
  std::replace(str.begin(), str.end(), 'c', ' ');
  std::cout << str << std::endl;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480