How to Replace a Substring in a String in c++ code

By | April 17, 2023

A bit away for from security themes just simple c++ coding related to string processing, changing substring in char array. Recently I had a task to hide some private info in log replacing it with asterisks. It is the code, I tried to do it the new substituted substring may longer or shorter then initial one. Also I implemented in single line using std::string.

#include 
#include 
#include
using namespace std;
int main(int n, char ** s )
{
        if(n<2)
        {
                printf("Specify name as argument\n");
                return -1;
        }
        char hello[]="Hello world!";
        printf("%s\n", hello);
        printf("%s\n", string(hello).replace(string(hello).find("world"), 5, s[1]).c_str());
        return 0;
}

Replacing with shorter substring:


./replace Alex
Hello world!
Hello Alex!

Replacing with longer substring:


./replace Maximilian
Hello world!
Hello Maximilian!

Leave a Reply

Your email address will not be published. Required fields are marked *