2016-03-20 27 views
0

私は、文字列の最初の半分を取得することができるよ:分割コマンドのstd ::文字列を使用してC++で文字列:: substrは

insert1 = tCreatureOne.substr(0, (tCreatureOne.length)/2 

私は、文字列の後半を取得する方法がわかりません

insert2 = tCreatureOne.substr((tCreatureOne.length)/2), ?????) 

ここは私のコードです。

// Insert creature two in to the 
//middle of creature one.Science! 
// Hamster and Emu make a HamEmuster 

std::string PerformScience(std::string tCreatureOne, std::string tCreatureTwo) 

{ 

    std::string insert1; 
    std::string insert2; 
    std::string insert3; 


     // first half : 0 to middle 

     insert1 = tCreatureOne.substr(0, (tCreatureOne.length)/2); 

    // last half: from middle to the end 
     insert2 = tCreatureOne.substr((tCreatureOne.length)/2), tCreatureOne.length); 

     insert3 = insert1 + tCreatureTwo + insert2; 

    return insert3; 
+1

もう一度 'substr()'を呼び出さないとできません! [this](http://stackoverflow.com/questions/236129/split-a-string-in-c)をチェックしてください。 – fordcars

+2

http://www.cplusplus.com/reference/string/string/substr/私はあなたが 'string :: npos'を探していると思っています。私。 'insert2 = tCreatureOne.substr((tCreatureOne.length)/ 2)、std :: string :: npos);' –

+4

@CraigYoung 'std :: string :: npos'はすでにデフォルトです。 2番目のパラメータを指定する必要はありません。 –

答えて

0

おそらく最も重要な開発者のスキルは、オンライン調査を行う方法を知っていることでしょう。 「C++ SUBSTR」のGoogle検索トップ結果としてこれを明らかに次のようにパラメータを説明http://www.cplusplus.com/reference/string/string/substr/

セクションにおいて、lenが記載されている:文字の

数ストリングに含める(ストリング場合可能な限り多くの文字が使用されます)。
string :: nposの値は、文字列の最後までのすべての文字を示します。

だから、あなたが書くことができます:

insert2 = tCreatureOne.substr(tCreatureOne.length()/2), std::string::npos); 

しかし、次のようにsubstrが宣言されていることに注意してください:nposからlenかなり便利なデフォルトを意味

string substr (size_t pos = 0, size_t len = npos) const;


したがって、あなたがより簡単に書くことができる:

insert2 = tCreatureOne.substr(tCreatureOne.length()/2)); 

をただし、次のようにsubstrは、「文字列の残りの部分を」を指定するなどの便利な手段を持っていなかった場合でも、あなたはまだ非常に簡単にそれを計算している可能性が:

int totalLength = tCreatureOne.length(); 
int firstLength = totalLength/2; 
int remainderLength = totalLength - firstLength; 

//So... 
insert2 = tCreatureOne.substr(tCreatureOne.length()/2), remainderLength); 
+0

私は間違いました。私はtCreatureOne.lengthの代わりにtCreatureOne.length()を書くべきです あなたの助けてくれてありがとう、本当に私が部分文字列のコマンドについてのすべてを理解して助けてくれてありがとうございました。 –

0

πάνταῥεῖは、彼らのコメントで正しいです - あなたの文字列の後半を取得するには、二番目のパラメータ(文字列の末尾)を指定する必要はありません。

insert2 = tCreatureOne.substr(tCreatureOne.length()/2); 

上の行は完全にうまく動作します。また、std::stringを使用しているので、括弧をlength()コールに追加することを忘れないでください。