Cpp - String String Replacing

Introduction

You can use the replace() to overwrite a substring.

The string lengths need not be identical.

The first two arguments is the starting position and the length of the substring to be replaced.

The third argument contains the replacement string.

string s1("this is a test!"), 
       s2("asdf"); 
int pos = s1.find("a");      
if( pos != string::npos ) 
    s1.replace(pos, 2, s2); 

If you only need to insert part of a string, you can use the fourth argument to define the starting position and the fifth to define the length of the substring.

string s1("this is a test!"), 
       s2("1234567890"); 
s1.replace(11, 4, s2, 0, 7); 

Demo

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

int main() //from   w  w w.  jav a 2s . c o m
{ 
    string s1("this is a test!"), 
           s2("asdf"); 
    int pos = s1.find("a");      
    if( pos != string::npos ) 
        s1.replace(pos, 2, s2); 

    cout << s1 << endl;    
    
    s1 = "this is a test!";
    s2 = "1234567890"; 
    s1.replace(11, 4, s2, 0, 7); 
    
    cout << s1 << endl;    
    return 0; 
}

Result