-5

I want to replace a string within a string with *, using this code to replace everything between he and ld in helloworld:

#include <string>
#include <iostream>

int main()
{  
       const std::string msg = "helloworld"; 

       const std::string from = "he";  

       const std::string to = "ld";  

       std::string s = msg;

       std::size_t startpos = s.find(from); 
       std::size_t endpos = s.find(to);  

       unsigned int l = endpos-startpos-2;  

       s.replace(startpos+2, endpos, l, '*');   

       std::cout << s;  
}

The output I got is He*****, but I wanted and expected He*****ld. What did I get wrong?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Ram Reddy
  • 13
  • 1
  • Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). –  May 25 '17 at 08:24
  • Please provide what you have tried!! – Sumeet May 25 '17 at 08:25
  • maybe this may help you it seems similar to your question: https://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string – Akhlaaq Badulla May 25 '17 at 08:29
  • 1
    The first parameters to `replace` is start and length of the replaced part, not start and end. `s.replace(startpos+2,l,l,'*'); ` seems to work. – Bo Persson May 25 '17 at 09:48

1 Answers1

1

You are replacing all the characters after index two. Count the indexes and replace only the range you want.

Try this:

#include <iostream>
#include <string>

int main ()
{
  //this one for replace
  string str="Hello World";

  // replace string added to this one
  string str2=str;
  // You can use string position.
  str2.replace(2,6,"******");

  cout << str2 << '\n';
  return 0;
}
  • First parameter for starting character
  • Second parameter for ending character
  • And Third parameter for string

There is a several ways you can do this. This is a one simple method.

UPDATE(After added your code):

Change:

unsigned int l=endpos-startpos-2;  
s.replace(startpos+2,endpos,l,'*'); 

To:

unsigned int l=endpos-3;
s.replace(startpos+2,l,l,'*');

Because your endpos store position of character d. You need to substract 3 by endpos then l variable value become 7. After that in replace() change second parameter to l.

read more about replace().

Blasanka
  • 21,001
  • 12
  • 102
  • 104