Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

stl

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.

like image 396
Bin Chen Avatar asked Dec 31 '25 09:12

Bin Chen


1 Answers

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

like image 133
Prasoon Saurav Avatar answered Jan 02 '26 00:01

Prasoon Saurav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!