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 回答