简体   繁体   English

C ++字符串添加

[英]C++ string addition

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;

Is there any better way to do it? 有没有更好的方法呢?

Thanks in advance. 提前致谢。

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. 有时这比更有效但更难阅读的解决方案“更好”。

An altogether different approach: 一种完全不同的方法:

#include <iostream>
#include <string>
#include <sstream>

int
main()
{
  std::string tmpstr("some string here");
  std::ostringstream out;
  out << head << tmpstr << tail;
  tmpstr = out.str(); // "headsome string heretail"

  return 0;
}

An advantage of this approach is that you can mix any type for which operator<< is overloaded and place them into a string. 这种方法的一个优点是你可以混合运算符<<被重载的任何类型并将它们放入一个字符串中。

  std::string tmpstr("some string here");
  std::ostringstream out;
  int head = tmpstr.length();
  char sep = ',';
  out << head << sep << tmpstr;
  tmpstr = out.str(); // "16,some string here"

You could append the tail and then cocatenate the string, like this: 您可以附加尾部然后共同定位字符串,如下所示:

tmpstr.append(tail);
tmpstr = head + tmpstr; 

It would probably be better to just create a new string at that point. 在那一点上创建一个新字符串可能会更好。

std::string finalstr(head.length() + tmpstr.length() + 1);
finalstr = head + tmpstr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM