Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation

Tags:

c++

string

Why it is possible to do

const string exclam = "!";
const string str = exclam + "Hello" + " world";

And not possible to do this:

const string exclam = "!";
const string str = "Hello" + " world" + exclam;

I know (although can't understand why) that it is not allowed to do:

const string str = "Hello" + " world" + "!";

as it will be interpreted like const char[6] + const char[6] + const char[1], so from other side, why this is not allowed also, or why it uses char[] and not string.

like image 612
NixDev Avatar asked Aug 28 '10 20:08

NixDev


People also ask

What is string concatenation example?

In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball".

What is string concatenation in C?

The concatenation of strings is a process of combining two strings to form a single string. If there are two strings, then the second string is added at the end of the first string.

What is string concatenation in Excel?

Use CONCATENATE, one of the text functions, to join two or more text strings into one string. Important: In Excel 2016, Excel Mobile, and Excel for the web, this function has been replaced with the CONCAT function.

Can we concatenate two strings?

In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.


1 Answers

The + operator is left-associative (evaluated left-to-right), so the leftmost + is evaluated first.

exclam is a std::string object that overloads operator+ so that both of the following perform concatenation:

exclam + "Hello"
"Hello" + exclam

Both of these return a std::string object containing the concatenated string.

However, if the first two thing being "added" are string literals, as in:

"Hello" + "World"

there is no class type object involved (there is no std::string here). The string literals are converted to pointers and there is no built-in operator+ for pointers.

like image 198
James McNellis Avatar answered Nov 15 '22 19:11

James McNellis