最佳方法创建一个包含几个变量大字符串?
-
21-09-2019 - |
题
我想创建一个包含许多变量的字符串:
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
,e.g:
#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();
其他提示
您可以使用boost ::格式如下:
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.");
这是一个有点难看,但它不涉及任何不需要的临时。
不隶属于 StackOverflow