如何在 c++ 中添加多个字符串
据我所知,C++ 只允许将 2 个字符串添加在一起,即: s = s1 + s2
但是如何将多个字符串相加呢?喜欢:
s = s1 + s2 + s3 + s4 + ... + sn
As I know that C++ only allows to add 2 strings together, i.e:s = s1 + s2
But how can I add many strings together? Like:
s = s1 + s2 + s3 + s4 + ... + sn
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您尝试附加 std::string 类的字符串对象,这应该可行。
或
If you're trying to append string objects of std::string class, this should work.
OR
首先,你可以很好地执行 +sn 操作。不过,假设您在 C++03 上使用
std::basic_string
字符串,则需要指数二次方(请参阅注释)时间。您可以将
std::basic_string::append
与std::basic_string::reserve
配合使用,以 O(n) 的时间连接字符串时间。编辑:例如
First of all, you can do the +sn thing just fine. Though it's going to take
exponentialquadradic(see comments) time assuming you're usingstd::basic_string<t>
strings on C++03.You can use the
std::basic_string<t>::append
in concert withstd::basic_string<t>::reserve
to concatenate your string in O(n) time.EDIT: For example
尽管它可能会创建很多临时对象(一个好的优化编译器应该会有所帮助),但它会起作用,因为它会有效地被解释为:
保证不创建临时对象的另一种方法是:
will work although it could create a lot of temporaries (a good optimizing compiler should help) because it will effectively be interpreted as:
An alternate way that is guaranteed not to create temporaries is:
std::ostringstream
是为此构建的,请参阅示例此处。这很简单:std::ostringstream
is build for that, see example here. It's easy:使用模板添加字符串、char* 和 char's 来形成字符串
strlen:-
附加字符串
main 示例
Use a template to add strings, char* and char's to form a string
strlen:-
appending strings
main example
如果您希望能够
那么这可以完成工作
如果你喜欢格式良好的东西
If you want to be able to do this
Then this will do the job
And if you like things nicely formatted