Concatenate Two String Literals

Concatenate two string literals


const string message = "Hello" + ",world" + exclam;

The + operator has left-to-right associativity, so the equivalent parenthesized expression is:

const string message = (("Hello" + ",world") + exclam);

As you can see, the two string literals "Hello" and ",world" are "added" first, hence the error.

One of the first two strings being concatenated must be a std::string object:

const string message = string("Hello") + ",world" + exclam;

Alternatively, you can force the second + to be evaluated first by parenthesizing that part of the expression:

const string message = "Hello" + (",world" + exclam);

It makes sense that your first example (hello + ",world" + "!") works because the std::string (hello) is one of the arguments to the leftmost +. That + is evaluated, the result is a std::string object with the concatenated string, and that resulting std::string is then concatenated with the "!".


As for why you can't concatenate two string literals using +, it is because a string literal is just an array of characters (a const char [N] where N is the length of the string plus one, for the null terminator). When you use an array in most contexts, it is converted into a pointer to its initial element.

So, when you try to do "Hello" + ",world", what you're really trying to do is add two const char*s together, which isn't possible (what would it mean to add two pointers together?) and if it was it wouldn't do what you wanted it to do.


Note that you can concatenate string literals by placing them next to each other; for example, the following two are equivalent:

"Hello" ",world"
"Hello,world"

This is useful if you have a long string literal that you want to break up onto multiple lines. They have to be string literals, though: this won't work with const char* pointers or const char[N] arrays.

How does concatenation of two string literals work?

It's defined by the ISO C standard, adjacent string literals are combined into a single one.

The language is a little dry (it is a standard after all) but section 6.4.5 String literals of C11 states:

In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed wide string literal tokens are concatenated into a single multibyte character sequence.

This is also mentioned in 5.1.1.2 Translation phases, point 6 of the same standard, though a little more succinctly:

Adjacent string literal tokens are concatenated.

This basically means that "abc" "def" is no different to "abcdef".

It's often useful for making long strings while still having nice formatting, something like:

const char *myString = "This is a really long "
"string and I don't want "
"to make my lines in the "
"editor too long, because "
"I'm basically anal retentive :-)";

How do I concatenate const/literal strings in C?

In C, "strings" are just plain char arrays. Therefore, you can't directly concatenate them with other "strings".

You can use the strcat function, which appends the string pointed to by src to the end of the string pointed to by dest:

char *strcat(char *dest, const char *src);

Here is an example from cplusplus.com:

char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");

For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];

Make sure that the first parameter has enough space to store what you're trying to copy into it. If available to you, it is safer to use functions like: strcpy_s and strcat_s where you explicitly have to specify the size of the destination buffer.

Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.

The return value of strcat can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:

strcat(strcat(str, foo), bar);

So your problem could be solved as follows:

char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);

How to concatenate two string in Dart?

There are 3 ways to concatenate strings

String a = 'a';
String b = 'b';

var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';

Usually string interpolation is preferred over the + operator.

There is also StringBuffer for more complex and performant string building.

Is there currently anyway to concatenate two or more string literal types to a single string literal type in TypeScript right now?

TS4.1+ answer:

You can now use template literal types to do this:

function makeKey<NS extends string, N extends string>(namespace: NS, name: N) {
return namespace + '/' + name as `${NS}/${N}`
}

const objKey = makeKey('admin', 'home');
// const objKey: "admin/home"

Playground link


Pre TS4.1 answer:

The answer is unfortunately no. There are several feature suggestions filed in GitHub that, if implemented, might give you such functionality (microsoft/TypeScript#12754 to augment keys during mapped types, or microsoft/TypeScript#6579 to manipulate string types via regular expressions) but I don't think they are being actively worked on. I don't see anything in the roadmap about it, anyway. If you really want to see this happen, you might want to go to one of those GitHub issues and give them a or describe your use case if it's particularly compelling. But I wouldn't hold my breath. Sorry!

Java String literals concatenation

In case of 2 and 3 , Compiler cannot calculate the value of String , since hill + i is a runtime statement , same for s1.length()

read here which i asked the same case - link

Think like this the String s1 and s2 are using compile time constant , s1="hill5" and s2="hill" + 5 , remember , string assigned as a literal is constant , its state cannot be modified , as String are immutable.

So at Compile time , compiler says "oh yeah , they are calculated as same value , i must assign the same reference to s1 and s2".

But in case of method two() and three() , compiler says " i dont know ,may be value of i can be changed any time , or s1.length() changes any time " , its a runtime thing , so compiler doesn't put s2 of two() and three() method in pool ,

Hence , they are false because at runtime , new object is created as soon it get changed right !!

Python string literal concatenation

Read the reference manual, it's in there.
Specifically:

Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings,

(emphasis mine)

This is why:

string = str("Some chars "
"Some more chars")

is exactly the same as: str("Some chars Some more chars").

This action is performed wherever a string literal might appear, list initiliazations, function calls (as is the case with str above) et-cetera.

The only caveat is when a string literal is not contained between one of the grouping delimiters (), {} or [] but, instead, spreads between two separate physical lines. In that case we can alternatively use the backslash character to join these lines and get the same result:

string = "Some chars " \
"Some more chars"

Of course, concatenation of strings on the same physical line does not require the backslash. (string = "Hello " "World" is just fine)


Is Python joining these two separate strings or is the editor/compiler treating them as a single string?

Python is, now when exactly does Python do this is where things get interesting.

From what I could gather (take this with a pinch of salt, I'm not a parsing expert), this happens when Python transforms the parse tree (LL(1) Parser) for a given expression to it's corresponding AST (Abstract Syntax Tree).

You can get a view of the parsed tree via the parser module:

import parser

expr = """
str("Hello "
"World")
"""
pexpr = parser.expr(expr)
parser.st2list(pexpr)

This dumps a pretty big and confusing list that represents concrete syntax tree parsed from the expression in expr:

-- rest snipped for brevity --

[322,
[323,
[3, '"hello"'],
[3, '"world"']]]]]]]]]]]]]]]]]],

-- rest snipped for brevity --

The numbers correspond to either symbols or tokens in the parse tree and the mappings from symbol to grammar rule and token to constant are in Lib/symbol.py and Lib/token.py respectively.

As you can see in the snipped version I added, you have two different entries corresponding to the two different str literals in the expression parsed.

Next, we can view the output of the AST tree produced by the previous expression via the ast module provided in the Standard Library:

p = ast.parse(expr)
ast.dump(p)

# this prints out the following:
"Module(body = [Expr(value = Call(func = Name(id = 'str', ctx = Load()), args = [Str(s = 'hello world')], keywords = []))])"

The output is more user friendly in this case; you can see that the args for the function call is the single concatenated string Hello World.

In addition, I also stumbled upon a cool module that generates a visualization of the tree for ast nodes. Using it, the output of the expression expr is visualized like this:

                                           expression tree for the given expression

Image cropped to show only the relevant part for the expression.

As you can see, in the terminal leaf node we have a single str object, the joined string for "Hello " and "World", i.e "Hello World".


If you are feeling brave enough, dig into the source, the source code for transforming expressions into a parse tree is located at Parser/pgen.c while the code transforming the parse tree into an Abstract Syntax Tree is in Python/ast.c.

This information is for Python 3.5 and I'm pretty sure that unless you're using some really old version (< 2.5) the functionality and locations should be similar.

Additionally, if you are interested in the whole compilation step python follows, a good gentle intro is provided by one of the core contributors, Brett Cannon, in the video From Source to Code: How CPython's Compiler Works.

Can a string literal be concatenated with a char*?

No. Concatenation of string literals is performed during translation (compilation). The operation you are requesting must be done within the program when it is executing. There is no provision for doing it automatically; you must write code to allocate space for the resulting string and to perform the concatenation.



Related Topics



Leave a reply



Submit