4

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

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.";

これにより、次のような文が生成されます。

フランクとジョーはナンシーと一緒にトランプをし、シャーロックはバイオリンを弾きました。

私の質問は:これを達成するための最適な方法は何ですか?+演算子を常に使用するのは非効率的であることが心配です。もっと良い方法はありますか?

4

3 に答える 3

8

はい、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();
于 2010-01-18T00:10:51.280 に答える
2

これにはboost::formatを使用できます。

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
)

これは、boost :: formatでできることの非常に単純な例であり、非常に強力なライブラリです。

于 2010-01-18T04:58:51.437 に答える
1

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

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

少し醜いですが、不必要な一時的なものは含まれていません。

于 2010-01-18T00:31:37.463 に答える