【问题标题】:Why does the replica work replace in c++? [duplicate]为什么副本工作在 C++ 中替换? [复制]
【发布时间】:2020-11-26 00:26:34
【问题描述】:

我开始学习 C++,我的任务是替换文本中的一些字符。类似于模板的东西下面是一些例子:

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

结果:

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

我试图用这段代码来做,但没有任何效果:

#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;
}

结果:

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

文本被插入到该行中,但该文本之后的所有内容都消失了。另外,有时我会使用俄语字符,它们是 UTF-8 编码的。 1 个符号更重。

【问题讨论】:

  • “1 个符号权重更多”是什么意思?

标签: c++


【解决方案1】:

std::string::replace(size_type pos, size_type count, const basic_string&amp; str);的第二个参数是

要被替换的子串的长度

例如在pos 之后和插入str 之前应该删除多少个字符。您只想替换 6 个字符。您的代码应如下所示:

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

另一方面,您应该在使用 find 之前检查它是否返回有效索引。

【讨论】:

  • text.find(): 14 js_code.length(): 28 你可以知道哪个代码是解决方案
  • @DimaTverdoy 恐怕我不明白你的评论。
猜你喜欢
  • 2019-11-29
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
相关资源
最近更新 更多