2

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.

4

2 回答 2

21

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.

于 2009-08-16T00:57:54.863 回答
1

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"
于 2009-08-16T06:54:13.540 回答