C ++字符串加法 [英] C++ string addition

查看:82
本文介绍了C ++字符串加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:如果我有一个字符串,并且想在其中添加首尾字符串(一个在开头,另一个在结尾),那么最好的方法是什么?像这样:

Simple question: If I have a string and I want to add to it head and tail strings (one in the beginning and the other at the end), what would be the best way to do it? Something like this:

std::string tmpstr("some string here");
std::string head("head");
std::string tail("tail");
tmpstr = head + tmpstr + tail;

还有更好的方法吗?

谢谢.

推荐答案

如果您担心效率并希望避免使用+运算符制作的临时副本,则可以执行以下操作:

If you were concerned about efficiency and wanted to avoid the temporary copies made by the + operator, then you could do:

tmpstr.insert(0, head);
tmpstr.append(tail);

如果您更加关注效率,则可以添加

And if you were even more concerned about efficiency, you might add

tmpstr.reserve(head.size() + tmpstr.size() + tail.size());

在进行插入/附加操作以确保任何重新分配操作仅发生一次之前.

before doing the inserting/appending to ensure any reallocation only happens once.

但是,您的原始代码简单易读.有时候,这比效率更高但更难阅读的解决方案更好".

However, your original code is simple and easy to read. Sometimes that's "better" than a more efficient but harder to read solution.

这篇关于C ++字符串加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆