简体   繁体   中英

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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