Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one char by another using std::string in C++?

Tags:

c++

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.

like image 557
Lucie kulza Avatar asked Mar 14 '14 10:03

Lucie kulza


1 Answers

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;
}
like image 70
juanchopanza Avatar answered Oct 27 '22 22:10

juanchopanza