创建包含多个变量的大字符串的最佳方法是什么?

5

我想创建一个包含许多变量的字符串:

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

这应该产生一个句子,读作:

弗兰克和乔与南希坐下来打牌,而福尔摩斯拉小提琴。

我的问题是:如何最优地完成这个任务?我担心不断使用 + 运算符会导致低效。有更好的方法吗?

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();

在过去的几个月里,我至少参考了这个答案10次。出于某种原因,我总是忘记。如果我可以给你更多的赞,我会的。 :) - Runcible

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可以做什么,它是一个非常强大的库。


1

您可以在临时对象上调用成员函数,例如operator+=。不幸的是,它具有错误的结合性,但我们可以通过括号来修复它。

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

这可能有点丑,但它不涉及任何不必要的临时变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接