创建包含多个变量的大字符串的最佳方法?
我想创建一个包含许多变量的字符串:
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.";
这应该生成一个句子,内容为
弗兰克和乔与南希一起坐下来打牌,而夏洛克拉小提琴。
我的问题是:最佳的是什么方法来完成这个?我担心不断使用 + 运算符效率低下。有更好的办法吗?
I want to create a string that contains many variables:
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.";
This should produce a sentence that reads
Frank and Joe sat down with Nancy to play cards, while Sherlock played the violin.
My question is: What is the optimal way to accomplish this? I am concerned that constantly using the + operator is ineffecient. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
std::stringstream
,例如:Yes,
std::stringstream
, e.g.:您可以使用 boost::format 来实现:
http:// www.boost.org/doc/libs/1_41_0/libs/format/index.html
这是一个非常简单的例子,说明了 boost::format 的功能,它是一个非常强大的库。
You could use boost::format for this:
http://www.boost.org/doc/libs/1_41_0/libs/format/index.html
This is is a very simple example of what boost::format can do, it is a very powerful library.
您可以在临时变量上调用诸如
operator+=
之类的成员函数。不幸的是,它的结合性是错误的,但我们可以用括号来修复它。它有点丑陋,但它不涉及任何不需要的临时对象。
You can call member functions like
operator+=
on temporaries. Unfortunately, it has the wrong associativity, but we can fix that with parenthesis.It's a little ugly, but it doesn't involve any unneeded temporaries.