Microsoft KB Archive/168377

= 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

 The Standard C++ Library, when used with:  Microsoft Visual C++ 4.2 Enterprise Edition

 Microsoft Visual C++ 4.2 Professional Edition

 Microsoft Visual C++ 5.0 Enterprise Edition

 Microsoft Visual C++ 5.0 Professional Edition</li></ul>

 Microsoft Visual C++ 6.0 Enterprise Edition</li></ul>

 Microsoft Visual C++ 6.0 Professional Edition</li></ul>

 Microsoft Visual C++ 6.0 Standard Edition</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q168377

<div class="symptoms_section">

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.

<div class="resolution_section">

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

<div class="status_section">

STATUS
This behavior is by design.

<div class="moreinformation_section">

Steps to reproduce the behavior
The sample code below demonstrates the behavior reported in the Symptoms section. 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:
 * 1) include
 * 2) include

s (should be 'acd'): add

Keywords: kbtshoot kbcodesnippet kbprogramming kbprb kbsample kbcode KB168377

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.