C++ string addition

给你一囗甜甜゛ 提交于 2021-01-27 21:28:17

问题


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.


回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/1283216/c-string-addition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!