std::字符串替换不保留结尾?

std::string replace not retaining the end?

本文关键字:结尾 保留 替换 字符串 std      更新时间:2023-10-16

我想用*替换字符串中的字符串,使用此代码替换helloworldheld之间的所有内容:

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

我得到的输出是He*****,但我想要并期望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;
}
  • 起始字符的第一个参数
  • 结束字符的第二个参数
  • 和字符串的第三个参数

有几种方法可以做到这一点。这是一种简单的方法。

更新(添加代码后):

改变:

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

自:

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

因为你的endpos存储位置的字符d。您需要将3减去endpos然后l变量值变为7。之后replace()将第二个参数更改为l.

阅读更多关于 replace()。