1

I started learning C ++ and my task is to replace some characters in the text. Something similar to the template Here are some examples:

<h1>Title</h1>$ js $<p>text...</p>

result:

<h1>Title</h1> </script>alert(1)</script> <p>text...</p>

I tried to do it with this code, but nothing worked:

#include <iostream>
#include <string>

using namespace std;

int main(){
    string text = "<h1>Title</h1>$ js $<p>text...</p>";
    string js_code = " </script>alert(1)</script> ";

    string result = text.replace(text.find("$ js $"), js_code.length(), js_code);

    cout << result << endl;

    return 0;
}

result:

<h1>Title</h1> </script>alert(1)</script>

The text was inserted into the line, but everything after this text disappeared. Also, sometimes I will use Russian characters, and they are in UTF-8 encoding. 1 Symbol weighs more.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207

1 Answers1

1

The second parameter of std::string::replace(size_type pos, size_type count, const basic_string& str); is the

length of the substring that is going to be replaced

e.g. how many characters should be removed after pos and before inserting str. You want to replace just 6 characters. Your code should look like this:

std::string pattern = "$ js $";
std::string result = text.replace(text.find(pattern), pattern.length(), js_code);

On another note you should check if find returns a valid index before using it.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30