最適な方法は、いくつかの変数を含む大規模な文字列を作成するには?

StackOverflow https://stackoverflow.com/questions/2083200

質問

私は多くの変数を含む文字列を作成したい:

std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";

std::string sentence;

sentence =   name1 + " and " + name2 + " sat down with " + name3;
sentence += " to play cards, while " + name4 + " played the violin.";

これは読み込み文を生成しなければならない。

シャーロックがバイオリンを演奏しながら、

フランクとジョーは、カードをプレイするためにナンシーに座った。

私の質問は次のとおりです。これを実現するための最適な方法は何ですか?私は常に+演算子を使用してineffecientであることを懸念しています。より良い方法はありますか?

役に立ちましたか?

解決

はい、std::stringstream、例えば:ます。

#include <sstream>
...

std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";

std::ostringstream stream;
stream << name1 << " and " << name2 << " sat down with " << name3;
stream << " to play cards, while " << name4 << " played the violin.";

std::string sentence = stream.str();

他のヒント

あなたはブースト::このためのフォーマットを使用することができます

http://www.boost.org/doc /libs/1_41_0/libs/format/index.htmlする

std::string result = boost::str(
    boost::format("%s and %s sat down with %s, to play cards, while %s played the violin")
      % name1 % name2 % name3 %name4
)

これは何ブーストの非常に単純な例です::フォーマットが行うことができますが、それは非常に強力なライブラリです。

あなたは一時にoperator+=のようなメンバ関数を呼び出すことができます。残念ながら、それは間違った関連性を持っているが、我々は括弧でこれを修正することができます。

std::string sentence(((((((name1  +  " and ")
                        += name2) += " sat down with ")
                        += name3) += " to play cards, while ")
                        += name4) += " played the violin.");

それは少し醜いですが、それは不要な一時を含まない。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top