2017-05-25 35 views
-5

我想*字符串中替换字符串,使用此代码在helloworld更换held之间的一切:std :: string替换不保留结束?

#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。 我得到了什么错误?

+0

请提供[最小,完整和可验证示例](https://stackoverflow.com/help/mcve)。 – InternetAussie

+0

请提供你已经尝试过的! – Sumeet

+0

也许这可能会帮助你看起来类似于你的问题: https://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string –

回答

1

您正在替换索引二后的所有字符。计算索引并仅替换您想要的范围。

试试这个:

#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; 
} 
  • 第一个参数为起始字符
  • 第二个参数为结束字符
  • 和第三参数字符串

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

UPDATE(后添加您的代码):

变化:

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

要:

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

因为你的性格dendpos储存位置。您需要通过endpos减去3,然后l变量值变为7。之后在replace()将第二个参数更改为l

阅读更多关于replace()

+0

请不要回答_off-topic_问题。您正在积极伤害网站的质量。 –

+0

我在离题前添加了这个答案。因此,只有在删除之前编辑答案才能匹配问题 – Blasanka

+0

问题在终止标记之前是_off-topic_,所以你想告诉我什么? –

相关问题