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.

3

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.