我想创建一个包含许多变量的字符串:
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.";
这应该产生一个读
的句子弗兰克和乔坐下来与南希打牌,而夏洛克则拉小提琴。
我的问题是:实现这一目标的最佳方法是什么?我担心不断使用+运算符是无效的。还有更好的方法吗?
答案 0 :(得分: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();
答案 1 :(得分: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可以做的一个非常简单的例子,它是一个非常强大的库。
答案 2 :(得分:1)
您可以在临时对象上调用operator+=
等成员函数。不幸的是,它具有错误的关联性,但我们可以用括号来解决这个问题。
std::string sentence(((((((name1 + " and ")
+= name2) += " sat down with ")
+= name3) += " to play cards, while ")
+= name4) += " played the violin.");
这有点难看,但它并不涉及任何不必要的临时工。