2017-05-25 37 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_,所以你想告訴我什麼? –

相關問題