Bin Chen
Bin Chen

Reputation: 63299

c++ string: is there good way to replace a char inside a string

I want to replace all the occurances of ' in a string to ^, but i saw string.replace is not the right function for me, do I need to write my own? It's boring.

Upvotes: 2

Views: 481

Answers (1)

Prasoon Saurav
Prasoon Saurav

Reputation: 92854

You can use std::replace from <algorithm> instead of using string::replace from <string>

Sample code

#include <iostream>
#include <algorithm>

int main()
{
   std::string s = "I am a string";
   std::replace(s.begin(),s.end(),' ',',');
   std::cout<< s;

} 

Output : I,am,a,string

Upvotes: 18

Related Questions