Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple std::string replace in C++

Tags:

c++

date

replace

I am using the following code for replacing special characters in a system date format in Windows OS.

But I can only replace one character.

Code:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string str("10/16/13");
    string str2("/");
    str.replace(str.find(str2),str2.length(),"-");
    cout << str << endl;
    return 0;
}

Output:

10-16/13
like image 373
user2754070 Avatar asked Nov 18 '25 06:11

user2754070


1 Answers

If you only want to replace single characters then you can use std::replace from the <algorithm> header:

std::replace(str.begin(), str.end(), '/', '-');

This will replace all '/' in your string by '-'.

like image 116
juanchopanza Avatar answered Nov 20 '25 21:11

juanchopanza



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!