C++ std::字符串替换不保留末端?

C++ std::字符串替换不保留末端?,c++,string,C++,String,我想用*替换字符串中的字符串,使用以下代码替换helloworld中he和ld之间的所有内容: 我得到的结果是他,但我想要并且期待他。 我做错了什么?您正在替换索引2之后的所有字符。计算索引并仅替换所需的范围 试试这个: #include <iostream> #include <string> int main () { //this one for replace string str="Hello World"; // replace string

我想用*替换字符串中的字符串,使用以下代码替换helloworld中he和ld之间的所有内容:

我得到的结果是他,但我想要并且期待他。
我做错了什么?

您正在替换索引2之后的所有字符。计算索引并仅替换所需的范围

试试这个:

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

因为您的endpos存储字符d的位置。您需要用endpos减去3,然后l变量值变为7。之后,在“替换”中将第二个参数更改为l


阅读更多信息。

请提供一个。请提供您尝试过的内容!!也许这有助于您解决与您的问题类似的问题:要替换的第一个参数是被替换零件的开始和长度,而不是开始和结束。s、 替换StartPos+2,l,l,“*”;似乎有效。请不要回答离题问题。你这样做是在积极地损害网站的质量。我在离题之前添加了这个答案。因此,在删除之前,只编辑答案以匹配问题。问题在最终标记之前已脱离主题。因此,您想告诉我什么?欢迎来到堆栈溢出。请花点时间阅读并参考您可以在此处询问的内容和方式。
#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;
}
unsigned int l=endpos-startpos-2;  
s.replace(startpos+2,endpos,l,'*'); 
unsigned int l=endpos-3;
s.replace(startpos+2,l,l,'*');