Knowledge Base

The replace function of the STL string class does not work as expected

Article ID: 168377

Article Last Modified on 9/2/2005


APPLIES TO


This article was previously published under Q168377

SYMPTOMS

The string::replace member function does not work as expected. This is because the same string object is used for modification and input. Many data manipulation routines do not check for overlapping or identical arguments, causing unexpected results.

RESOLUTION

Create a temporary copy of the string as shown below:
s1.replace (1,2,string("c"));
				

STATUS

This behavior is by design.

MORE INFORMATION

Steps to reproduce the behavior

The sample code below demonstrates the behavior reported in the Symptoms section.
#include <iostream>
#include <string>
using namespace std ;
void f1()
 {
  string s ("abcd");
  s.replace (1,2,s,2,1);
  cout << "s (should be 'acd'): " << s << endl << endl;
 }
int main ()
 {
   f1();// prints "add" instead of "acd"
   return 0 ;
 }
				
The output is the following:

s (should be 'acd'): add

Keywords: kbtshoot kbcodesnippet kbprogramming kbprb kbsample kbcode KB168377