2017-05-25 4 views
-5

私はhelloworldheldの間のすべてを置き換えるために、このコードを使用して、*で文字列内の文字列を置換したい: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

インデックス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; 
} 
  • 文字
  • 文字
  • を終了するための2番目のパラメータと文字列

のための三番目のパラメータを開始するための最初のパラメータをこれを行う。これは簡単な方法の1つです。 (後にあなたのコードを追加しました)

UPDATE:

変更:

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

へ:

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

文字dのごendpos店舗の位置からです。 3endposで引いて、lの値が7になるようにする必要があります。その後、replace()の2番目のパラメータをlに変更します。

続きを読むreplace()を参照してください。

+0

_off-topic_の質問には答えないでください。あなたは積極的にサイトの品質を傷つけています。 –

+0

トピック前にこの回答を追加しました。だから、削除する前に質問にマッチする答えを編集しただけです – Blasanka

+0

最後にマークされる前に質問が_off-topic_だったので、何を教えていますか? –

関連する問題