Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++11 offer a better way to concatenate strings on the fly?

I've seen this answer, and I wonder (I hope) if C++11 has come up with a native better method to concatenate, and possibly format, strings.

With "better" I mean actually really one-line, like in pretty much all higher level languages (bonus points if it supports something like python's "formatted string"%(tuple) syntax but I guess that's really hoping for too much).

The ideal result should be something like:

my_func("bla bla bla" << int(my_int) << "bla bla bla"); 

The only barely acceptable methods listed in that answer are the fastformat ones, but I wonder if C++11 managed to do better.

like image 646
o0'. Avatar asked Mar 19 '12 17:03

o0'.


People also ask

What is the most efficient way to concatenate many strings together?

If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.

What is the correct way to concatenate the strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Does C support string concatenation?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

Is string concatenation slow in C++?

Strings, C++'s std::strings are mutable, and therefore can be built through simple concatenation just as fast as through other methods.


1 Answers

C++11 introduces to_string() functions:

my_func("bla bla bla" + to_string(my_int) + "bla bla bla"); 
like image 56
bames53 Avatar answered Oct 15 '22 16:10

bames53