String concatenation: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add Ecstasy example)
 
(289 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
[[Category:String manipulation]]
{{task|Basic language learning}}[[Category:String manipulation]]Set a string variable equal to any text value. Print it to the console concatenated with a string literal. Create a new string variable whose value is the other variable concatenated with a string literal. Print this new variable.
[[Category: String manipulation]]
{{basic data operation}}
[[Category:Simple]]

{{task|Basic language learning}}

;Task:
Create a string variable equal to any text value.

Create another string variable whose value is the original variable concatenated with another string literal.

To illustrate the operation, show the content of the variables.

{{Template:Strings}}
<br><br>

=={{header|11l}}==
{{trans|Python}}

<syntaxhighlight lang="11l">V s1 = ‘hello’
print(s1‘ world’)
V s2 = s1‘ world’
print(s2)</syntaxhighlight>

{{out}}
<pre>
hello world
hello world
</pre>

=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program concatStr64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessFinal: .asciz "The final string is \n"
szString: .asciz "Hello "
szString1: .asciz " the world. \n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
szFinalString: .skip 255
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
// load string
ldr x1,qAdrszString
ldr x2,qAdrszFinalString
mov x4,0
1:
ldrb w0,[x1,x4] // load byte of string
strb w0,[x2,x4]
cmp x0,0 // compar with zero ?
add x3,x4,1
csel x4,x3,x4,ne // if x0 <> 0 x4 = x4 +1 sinon x4
bne 1b
ldr x1,qAdrszString1
mov x3,0
2:
ldrb w0,[x1,x3] // load byte of string 1
strb w0,[x2,x4]
cmp x0,0 // compar with zero ?
add x5,x4,1
csel x4,x5,x4,ne
add x5,x3,1
csel x3,x5,x3,ne
bne 2b
mov x0,x2 // display final string
bl affichageMess
100: // standard end of the program */
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszString: .quad szString
qAdrszString1: .quad szString1
qAdrszFinalString: .quad szFinalString
qAdrszMessFinal: .quad szMessFinal
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Hello the world.
</pre>

=={{header|ABAP}}==
<syntaxhighlight lang="abap">DATA: s1 TYPE string,
s2 TYPE string.

s1 = 'Hello'.
CONCATENATE s1 ' literal' INTO s2 RESPECTING BLANKS.
WRITE: / s1.
WRITE: / s2.
</syntaxhighlight>
{{out}}
<pre>
Hello
Hello literal
</pre>
===Another way===
<syntaxhighlight lang="abap">REPORT string_concatenation.

DATA(var1) = 'Hello'.
DATA(var2) = 'Literal'.

cl_demo_output=>new(
)->begin_section( 'String concatenation using |{ }|'
)->write( 'Statement: |{ var1 } { var2 }|'
)->write( |{ var1 } { var2 }|
)->begin_section( 'String concatenation with new string'
)->write( 'Statement: |{ var1 } world!|'
)->write( |{ var1 } world!|
)->display( ).
</syntaxhighlight>
{{out}}
<pre>
Hello literal
Hello world!
</pre>

=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Append(CHAR ARRAY text,suffix)
BYTE POINTER srcPtr,dstPtr
BYTE len

len=suffix(0)
IF text(0)+len>255 THEN
len=255-text(0)
FI
IF len THEN
srcPtr=suffix+1
dstPtr=text+text(0)+1
MoveBlock(dstPtr,srcPtr,len)
text(0)==+suffix(0)
FI
RETURN

PROC Concatenate(CHAR ARRAY text,left,right)
SCopy(text,left)
Append(text,right)
RETURN

PROC TestConcatenate(CHAR ARRAY left,right)
CHAR ARRAY text(256)

Concatenate(text,left,right)
PrintF("""%S""+""%S""=""%S""%E",left,right,text)
RETURN

PROC Main()
TestConcatenate("Hello", " World!")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_concatenation.png Screenshot from Atari 8-bit computer]
<pre>
"Hello"+" World!"="Hello World!"
</pre>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>package
<syntaxhighlight lang="actionscript">package
{
{
public class Str
public class Str
Line 14: Line 189:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure String_Concatenation is
procedure String_Concatenation is
S : String := "Hello";
S1 : constant String := "Hello";
S2 : constant String := S1 & " literal";
begin
begin
Put_Line (S & " literal");
Put_Line (S1);
Put_Line (S2);
declare
end String_Concatenation;</syntaxhighlight>
S1 : String := S & " literal";
{{out|Sample output}}
begin
Put_Line (S1);
end;
end String_Concatenation;</lang>
Sample output:
<pre>
<pre>
Hello literal
Hello
Hello literal
Hello literal
</pre>
</pre>

=={{header|Aime}}==
<syntaxhighlight lang="aime">text s, v;

s = "Hello";
o_(s, "\n");
v = s + ", World!";
o_(v, "\n");</syntaxhighlight>
{{out}}
<pre>Hello
Hello, World!</pre>

=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - no extensions to language used}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<syntaxhighlight lang="algol68">STRING s := "hello";
print ((s + " literal", new line));
STRING s1 := s + " literal";
print ((s1, new line))</syntaxhighlight>
{{out}}
<pre>
hello literal
hello literal
</pre>

=={{header|ALGOL-M}}==
<syntaxhighlight lang="algol">
begin

comment
The string concatenation operator is ||, and the
default string length is 10 characters unless a
longer length (up to 255) is explicitly declared;

string(20) s1, s2;

s1 := "Hello";
write (s1 || ", world");

s2 := s1 || ", world";
write (s2);

end
</syntaxhighlight>
{{out}}
<pre>
Hello, world
Hello, world
</pre>



=={{header|Apex}}==

<syntaxhighlight lang="apex">
String s1 = 'Hello ';
String s2 = 'Salesforce Developer!';

String s3 = s1+s2;

// Print output
System.debug(s3);</syntaxhighlight>
{{out}}
<pre>Hello Salesforce Developer!</pre>

=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">try
set endMsg to "world!"
set totMsg to "Hello, " & endMsg
display dialog totMsg
end try</syntaxhighlight>

=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program strConcat.s */

/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessFinal: .asciz "The final string is \n"

szString: .asciz "Hello "
szString1: .asciz " the world. \n"

/* UnInitialized data */
.bss
szFinalString: .skip 255

/* code section */
.text
.global main
main:
@ load string
ldr r1,iAdrszString
ldr r2,iAdrszFinalString
mov r4,#0
1:
ldrb r0,[r1,r4] @ load byte of string
strb r0,[r2,r4]
cmp r0,#0 @ compar with zero ?
addne r4,#1
bne 1b
ldr r1,iAdrszString1
mov r3,#0
2:
ldrb r0,[r1,r3] @ load byte of string 1
strb r0,[r2,r4]
cmp r0,#0 @ compar with zero ?
addne r4,#1
addne r3,#1
bne 2b
mov r0,r2 @ display final string
bl affichageMess
100: @ standard end of the program */
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszString: .int szString
iAdrszString1: .int szString1
iAdrszFinalString: .int szFinalString
iAdrszMessFinal: .int szMessFinal

/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres
bx lr @ return

</syntaxhighlight>

=={{header|Arturo}}==
<syntaxhighlight lang="rebol">str1: "Hello "
str2: "World"
print str1 ++ str2 ++ "!"</syntaxhighlight>

{{out}}

<pre>Hello World!</pre>

=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">string s1 = "Hello";
write(s1 + " World!");
write(s1, " World!");
string s2 = s1 + " World!";
write(s2);</syntaxhighlight>

=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>s := "hello"
<syntaxhighlight lang="autohotkey">s := "hello"
Msgbox, %s%
Msgbox, %s%
s1 := s . " literal" ;the . is optional
s1 := s . " literal" ;the . is optional
Msgbox, %s1%</lang>
Msgbox, %s1%</syntaxhighlight>

=={{header|AWK}}==
=={{header|AWK}}==
The AWK concatenation operator is just a space.
The AWK concatenation operator is nothing.
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
s = "hello"
s = "hello"
print s " literal"
print s " literal"
s1 = s " literal"
s1 = s " literal"
print s1
print s1
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|Axe}}==
<syntaxhighlight lang="axe">Lbl CONCAT
<lang algol68>STRING s := "hello";
Copy(r₁,L₁,length(r₁))
print ((s + " literal", new line));
Copy(r₂,L₁+length(r₁),length(r₂)+1)
STRING s1 := s + " literal";
L₁
print ((s1, new line))</lang>
Return</syntaxhighlight>
Output:<lang algol68>hello literal
hello literal</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{works with|BASIC256}}
<lang qbasic>s$ = "hello"
{{works with|Liberty BASIC}}
print s$;" literal" 'or s$ + " literal"
{{works with|QB64}}
{{works with|Run Basic}}
{{works with|Yabasic}}
<syntaxhighlight lang="qbasic">s$ = "hello"
print s$ + " literal"
s2$ = s$ + " literal"
s2$ = s$ + " literal"
print s2$</lang>
print s$
print s2$</syntaxhighlight>
Output:
{{out}}
<pre>hello literal
<pre>hello literal
hello
hello literal</pre>
hello literal</pre>

==={{header|Applesoft BASIC}}===

A semicolon (;) is ''not'' the same as a concatenate operator (+), it is an instruction that works only on the <code>PRINT</code> statement to suppress newlines at the end of a literal or series of literals. For example, the instruction <code>S$="HELLO";"LITERAL"</code> would result in a syntax error.

<syntaxhighlight lang="applesoftbasic">10 S$ = "HELLO"
20 PRINT S$ + " LITERAL"
30 PRINT S$
40 S2$ = S$ + " LITERAL"
50 PRINT S2$</syntaxhighlight>

{{out}}
<pre>HELLO LITERAL
HELLO
HELLO LITERAL</pre>

==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">
A$ = "hello"
PRINT A$," World"

A2$ = A$ & " using & to concat World"
PRINT A2$
</syntaxhighlight>

==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> stringvar1$ = "Hello,"
stringvar2$ = stringvar1$ + " world!"
PRINT "Variable 1 is """ stringvar1$ """"
PRINT "Variable 2 is """ stringvar2$ """"</syntaxhighlight>
{{out}}
<pre>Variable 1 is "Hello,"
Variable 2 is "Hello, world!"</pre>

==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 LET S$="Hello"
110 LET S$=S$&" world!"
120 PRINT S$</syntaxhighlight>

==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">s1$ = "Hello"
print s1$; " World!"
print s1$ + " World!"
print s1$ & " World!"
s2$ = s1$; " World!"
print s2$
s2$ = s1$ + " World!"
print s2$
s2$ = s1$ & " World!"
print s2$</syntaxhighlight>

==={{header|Run BASIC}}===
{{works with|Liberty BASIC}}
<syntaxhighlight lang="runbasic">s1$ = "Hello"
print s1$; " World!"
print s1$ + " World!"
s2$ = s1$; " World!"
print s2$
s2$ = s1$ + " World!"
print s2$</syntaxhighlight>

==={{header|True BASIC}}===
{{works with|BASIC256}}
<syntaxhighlight lang="qbasic">LET s1$ = "Hello"
PRINT s1$; " World!"
PRINT s1$ + " World!"
LET s2$ = s1$ & " World!"
PRINT s2$
END</syntaxhighlight>

==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">s = Dup("Hello")
Print Show(s); " World!"
Print Show(Join(s, " World!"))
t = Join(s, " World!")
Print Show(t)
End</syntaxhighlight>
==={{header|Yabasic}}===
{{works with|Liberty BASIC}}
{{works with|QB64}}
{{works with|QBasic}}
{{works with|Run BASIC}}
<syntaxhighlight lang="yabasic">s1$ = "Hello"
print s1$, " World!"
print s1$ + " World!"
s2$ = s1$ + " World!"
print s2$</syntaxhighlight>

==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">10 LET s$="Hello"
20 LET s$=s$+" World!"
30 PRINT s$</syntaxhighlight>

=={{header|Batch File}}==
<syntaxhighlight lang="dos">set string=Hello
echo %string% World
set string2=%string% World
echo %string2%</syntaxhighlight>

=={{header|Beef}}==
<syntaxhighlight lang="csharp">using System;
namespace StringConcatenation
{
class Program {
static void Main() {
String s = scope ("hello");
Console.Write(s);
Console.WriteLine(" literal");
s.Append(" literal");
Console.WriteLine(s);
}
}
}
</syntaxhighlight>

=={{header|BQN}}==
<code>∾</code>(Join) will concatenate two strings together.

<syntaxhighlight lang="bqn">str ← "Hello "
newstr ← str ∾ "world"
•Show newstr</syntaxhighlight>
<syntaxhighlight lang="bqn">"Hello world"</syntaxhighlight>

=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">"Hello ":?var1
& "World":?var2
& str$(!var1 !var2):?var12
& put$("var1=" !var1 ", var2=" !var2 ", var12=" !var12 "\n")</syntaxhighlight>
{{out}}
<pre>var1= Hello , var2= World , var12= Hello World</pre>

=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">blsq ) "Hello, ""world!"?+
"Hello, world!"</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 91: Line 572:
puts(s2);
puts(s2);
free(s2);
free(s2);
}</lang>
}</syntaxhighlight>

=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;

class Program {
static void Main(string[] args) {
var s = "hello";
Console.Write(s);
Console.WriteLine(" literal");
var s2 = s + " literal";
Console.WriteLine(s2);
}
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>


Line 103: Line 597:
std::cout << s2 << std::endl;
std::cout << s2 << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
Output:
<pre>hello literal
<pre>hello literal
hello literal</pre>
hello literal</pre>


=={{header|C sharp|C#}}==
=={{header|ChucK}}==
<syntaxhighlight lang="text">
"Hello" => string A;
A + " World!" => string B;
<<< B >>>;
</syntaxhighlight>
{{out}}
<pre>"Hello World!"</pre>


=={{header|Clojure}}==
<lang csharp>using System;
<syntaxhighlight lang="lisp">(def a-str "abcd")
(println (str a-str "efgh"))


(def a-new-str (str a-str "efgh"))
class Program {
(println a-new-str)</syntaxhighlight>
static void Main(string[] args) {
string s = "hello";
Console.WriteLine(s + " literal");
string s2 = s + " literal";
Console.WriteLine(s2);
}
}</lang>


=={{header|Clojure}}==
=={{header|COBOL}}==
With the <code>STRING</code> verb:
<lang lisp>(def a-str "abcd")
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
(println (apply str (concat a-str "efgh")))
PROGRAM-ID. Concat.
(def a-new-str (apply str (concat a-str "efgh")))

(println a-new-str)</lang>
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Str PIC X(7) VALUE "Hello, ".
01 Str2 PIC X(15).

PROCEDURE DIVISION.
DISPLAY "Str : " Str
STRING Str " World!" DELIMITED BY SIZE INTO Str2
DISPLAY "Str2 : " Str2

GOBACK
.</syntaxhighlight>
Alternate method using the <code>CONCATENATE</code> intrinsic function:
<syntaxhighlight lang="cobol"> ...
PROCEDURE DIVISION.
DISPLAY "Str : " Str
MOVE FUNCTION CONCATENATE(Str, " World!") TO Str2
DISPLAY "Str2 : " Str2

GOBACK
.</syntaxhighlight>

String literals can also be concatenated in the follwing ways:
<syntaxhighlight lang="cobol">* *> Using a '&'.
01 Long-Str-Val PIC X(200) VALUE "Lorem ipsum dolor sit "
& "amet, consectetuer adipiscing elit, sed diam nonummy "
& "nibh euismod tincidunt ut laoreet dolore magna aliquam "
& "erat volutpat.".

* *> Using a '-' in column 7. Note the first two literals have no
* *> closing quotes.
01 Another-Long-Str PIC X(200) VALUE " Ut wisi enim ad minim
- "veniam, quis nostrud exerci tation ullamcorper suscipit
- "lobortis nisl ut aliquip ex ea commodo consequat".</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(let ((s "hello"))
<syntaxhighlight lang="lisp">(let ((s "hello"))
(format t "~a there!~%" s)
(format t "~a there!~%" s)
(let* ((s2 " there!")
(let* ((s2 " there!")
(s (concatenate 'string s s2)))
(s (concatenate 'string s s2)))
(format t "~a~%" s)))</lang>
(format t "~a~%" s)))</syntaxhighlight>
<syntaxhighlight lang="lisp">(defparameter *s* "hello")

<lang lisp>(defparameter *s* "hello")
(print (concatenate 'string *s* " literal"))
(print (concatenate 'string *s* " literal"))
(defparameter *s1* (concatenate 'string *s* " literal"))
(defparameter *s1* (concatenate 'string *s* " literal"))
(print *s1*)</lang>
(print *s1*)</syntaxhighlight>

=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE StringConcatenation;
IMPORT StdLog;

PROCEDURE Do*;
VAR
str1,str2: ARRAY 128 OF CHAR;
BEGIN
str1 := "Hello";
str2 := str1 + " world";
StdLog.String(":> " + str2);StdLog.Ln
END Do;

END StringConcatenation.
</syntaxhighlight>
Execute: ^Q StringConcatenation.Do<br/>
{{out}}
<pre>
:> Hello world
</pre>


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio;
<lang d>string s = "hello";
writefln(s ~ " world");
void main() {
auto s2 = s ~ " world";
string s = "hello";
writefln(s2);</lang>
writeln(s ~ " world");
auto s2 = s ~ " world";
writeln(s2);
}</syntaxhighlight>


=={{header|E}}==
=={{header|DCL}}==
<syntaxhighlight lang="dcl">$ string1 = "hello"
<lang e>def a := "rose"
$ string2 = string1 + " world"
println(a + "bud")
$ show symbol string*</syntaxhighlight>
def b := a + "tte"
{{out}}
println(b)</lang>
<pre> STRING1 = "hello"
STRING2 = "hello world"</pre>

=={{header|Delphi}}==
<syntaxhighlight lang="delphi">program Concat;

{$APPTYPE CONSOLE}

var
s1, s2: string;
begin
s1 := 'Hello';
s2 := s1 + ' literal';
WriteLn(s1);
WriteLn(s2);
end.</syntaxhighlight>

=={{header|DWScript}}==
<syntaxhighlight lang="delphi">var s1 := 'Hello';
var s2 := s1 + ' World';

PrintLn(s1);
PrintLn(s2);</syntaxhighlight>

=={{header|Dyalect}}==

{{trans|Swift}}

<syntaxhighlight lang="dyalect">var s = "hello"
print(s + " literal")
var s1 = s + " literal"
print(s1)</syntaxhighlight>

=={{header|Dylan.NET}}==
<syntaxhighlight lang="dylan.net">
//to be compiled using dylan.NET v. 11.5.1.2 or later.
#refstdasm mscorlib.dll

import System

assembly concatex exe
ver 1.3.0.0

class public Program

method public static void main()
var s as string = "hello"
Console::Write(s)
Console::WriteLine(" literal")
var s2 as string = s + " literal"
Console::WriteLine(s2)
end method

end class</syntaxhighlight>

=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">local :s1 "hello"
local :s2 concat( s1 ", world" )
!print s2</syntaxhighlight>
{{out}}
<pre>hello, world</pre>

=={{header|EasyLang}}==
<syntaxhighlight lang="text">a$ = "hello"
b$ = a$ & " world"
print b$</syntaxhighlight>

=={{header|Ecstasy}}==
<syntaxhighlight lang="ecstasy">
module StringAppend {
void run() {
String start = "hello";
String finish = " world";

// approach #1: add strings together
String approach1 = start + finish;

// approach #2: StringBuffer
String approach2 = new StringBuffer()
.append(start)
.append(finish)
.toString();

// approach #3: string template
String approach3 = $"{start}{finish}";

@Inject Console console;
console.print($|
|Appending strings:
|
| {start=}
| {finish=}
|
| {approach1=}
| {approach2=}
| {approach3=}
|
);
}
}
</syntaxhighlight>

{{out}}
<pre>
x$ xec doc/examples/StringAppend

Appending strings:

start=hello
finish= world

approach1=hello world
approach2=hello world
approach3=hello world
</pre>

=={{header|Ela}}==
Strings in Ela support a polymorphic concatenation operator (++):
<syntaxhighlight lang="ela">hello = "Hello"
hello'world = hello ++ ", " ++ "world"
(hello, hello'world)</syntaxhighlight>
{{out}}
<pre>("Hello", "Hello, world!")</pre>
However, as long as strings in Ela are indexed arrays, this operator is not very effective for
a large number of concatenations. Therefore one can use an alternate technique (a pure StringBuilder
type defined in standard prelude). The resulting code would look like so:
<syntaxhighlight lang="ela">toString $ "Hello" +> ", " +> "world"</syntaxhighlight>
The (+>) token is a type constructor. Therefore the result of its application is an instance of type
StringBuilder. In order to produce a string one should call a polymorphic toString function at the end
as shown above.

=={{header|Elena}}==
ELENA 6.x:
<syntaxhighlight lang="elena">public program()
{
var s := "Hello";
var s2 := s + " literal";
console.writeLine(s);
console.writeLine(s2);
console.readChar()
}</syntaxhighlight>
{{out}}
<pre>
Hello
Hello literal
</pre>

=={{header|EMal}}==
<syntaxhighlight lang="emal">
text s = "hello"
write(s)
writeLine(" literal")
text s2 = s + " literal"
writeLine(s2)
</syntaxhighlight>
{{out}}
<pre>
hello literal
hello literal
</pre>

=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
s = "hello"
t = s <> " literal"

IO.puts s
IO.puts t
</syntaxhighlight>
{{out}}
<pre>
hello
hello literal
</pre>

=={{header|Emacs Lisp}}==

<syntaxhighlight lang="lisp">(defvar foo "foo")
(defvar foobar (concat foo "bar"))
(message "%sbar" foo)
(message "%s" foobar)</syntaxhighlight>

{{out}}

foobar
foobar

=={{header|Erlang}}==
<syntaxhighlight lang="erlang">S = "hello",
S1 = S ++ " literal",
io:format ("~s literal~n",[S]),
io:format ("~s~n",[S1])</syntaxhighlight>
{{out|Sample output}}
<pre>
hello literal
hello literal
</pre>

=={{header|ERRE}}==
<syntaxhighlight lang="erre">
..........
S$="HELLO"
PRINT(S$;" LITERAL") ! or S$+" LITERAL"
S2$=S$+" LITERAL"
PRINT(S2$)
..........
</syntaxhighlight>

=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">sequence s, s1
s = "hello"
puts(1, s & " literal")
puts(1,'\n')
s1 = s & " literal"
print (1, s1))
puts(1,'\n')</syntaxhighlight>
{{out}}
hello literal
hello literal

=={{header|Excel}}==
Take three cells, say A1,B1 and C1. In C1, type in :

<syntaxhighlight lang="excel">

=CONCATENATE(A1;" ";B1)

</syntaxhighlight>

As the text in A1 and/or B1 is changed, C1 will be updated.

<syntaxhighlight lang="text">
Hello World Hello World
</syntaxhighlight>

=={{header|F_Sharp|F#}}==
{{trans|C#}}
<syntaxhighlight lang="fsharp">open System

[<EntryPoint>]
let main args =
let s = "hello"
Console.Write(s)
Console.WriteLine(" literal")
let s2 = s + " literal"
Console.WriteLine(s2)
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"wake up" [ " sheeple" append print ] [ ", you sheep" append ] bi print</lang>
<syntaxhighlight lang="factor">"wake up" [ " sheeple" append print ] [ ", you sheep" append ] bi print</syntaxhighlight>

=={{header|Falcon}}==
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic''
<syntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */

s = "critical"
> s + " literal"
s2 = s + " literal"
> s2
</syntaxhighlight>
{{out}}
<pre>
critical literal
critical literal
[Finished in 0.2s]
</pre>

=={{header|Fantom}}==
Illustrating in <tt>fansh</tt>:
<syntaxhighlight lang="fantom">fansh> a := "abc"
abc
fansh> b := a + "def"
abcdef
fansh> a
abc
fansh> b
abcdef</syntaxhighlight>

<syntaxhighlight lang="java">
/* gary chike 08/27/2023 */

class Main
{
static Void main() {
s1 := "Only The"
s2 := "knows"
s3 := s1 + " Fantom " + s2 + "!" // Concatenation
echo(s3)
s4 := "$s1 Fantom $s2!" // String interpolation
echo(s4)
}
}
</syntaxhighlight>

{{out}}
<pre>
Only The Fantom knows!
Only The Fantom knows!
</pre>

=={{header|Fe}}==
'''pack''' is not a built-in function, see its definition [[Reverse_a_string#Fe|here]].
<syntaxhighlight lang="clojure">
(print (pack '("Hello" " world!")))
</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>s" hello" pad place
<syntaxhighlight lang="forth">s" hello" pad place
pad count type
pad count type
s" there!" pad +place \ +place is called "append" on some Forths
s" there!" pad +place \ +place is called "append" on some Forths
pad count type</lang>
pad count type</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>program StringConcatenation
<syntaxhighlight lang="fortran">program StringConcatenation


integer, parameter :: maxstringlength = 64
integer, parameter :: maxstringlength = 64
character (*), parameter :: s = "hello"
character (maxstringlength) :: s1, s = "hello"
character (maxstringlength) :: s1


print *,s // " literal"
print *,s // " literal"
s1 = s // " literal"
s1 = trim(s) // " literal"
print *,s1
print *,s1


end program</lang>
end program</syntaxhighlight>

=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64

Var s1 = "String"
Var s2 = s1 + " concatenation"
Print s1
Print s2
Sleep</syntaxhighlight>

{{out}}
<pre>
String
String concatenation
</pre>

=={{header|Frink}}==
<syntaxhighlight lang="frink">
a = "Frink"
b = a + " rules!"
println[b]
</syntaxhighlight>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1

CFStringRef s1, s2

s1 = @"any text value "
print s1

s2 = fn StringByAppendingString( s1, @"another string literal" )
print s2

HandleEvents</syntaxhighlight>

=={{header|Gambas}}==
In gambas, the ampersand symbol is used as a concatenation operator:

'''[https://gambas-playground.proko.eu/?gist=098450adbbe0e284f0b9cdac67d74dda Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public sub main()
DIM bestclub AS String
DIM myconcat AS String

bestclub = "Liverpool"
myconcat = bestclub & " Football Club"

Print myconcat

End</syntaxhighlight>

=={{header|GDScript}}==
{{works with|Godot|4.0.1}}

<syntaxhighlight lang="gdscript">
extends MainLoop


func _process(_delta: float) -> bool:
var first: String = "123"
var second: String = first + "abc"

print(first)
print(second)

return true # Exit
</syntaxhighlight>

=={{header|GlovePIE}}==
<syntaxhighlight lang="glovepie">var.text1="Hello, "
debug=var.text1+"world!"</syntaxhighlight>

=={{header|Go}}==
<syntaxhighlight lang="go">package main

import "fmt"

func main() {
// text assigned to a string variable
s := "hello"

// output string variable
fmt.Println(s)

// this output requested by original task descrption, although
// not really required by current wording of task description.
fmt.Println(s + " literal")

// concatenate variable and literal, assign result to another string variable
s2 := s + " literal"

// output second string variable
fmt.Println(s2)
}</syntaxhighlight>
{{out}}
<pre>
hello
hello literal
hello literal
</pre>

=={{header|Golfscript}}==
<syntaxhighlight lang="golfscript">"Greetings ":s;
s"Earthlings"+puts
s"Earthlings"+:s1;
s1 puts</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def s = "Greetings "
<syntaxhighlight lang="groovy">def s = "Greetings "
println s + "Earthlings"
println s + "Earthlings"


def s1 = s + "Earthlings"
def s1 = s + "Earthlings"
println s1</lang>
println s1</syntaxhighlight>
{{out}}

Output:
<pre>Greetings Earthlings
<pre>Greetings Earthlings
Greetings Earthlings</pre>
Greetings Earthlings</pre>

=={{header|Halon}}==
The dot (concatenation) operator may cast datatypes to strings.
<syntaxhighlight lang="halon">echo "Hello" . "World " . 123;</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.IO
<syntaxhighlight lang="haskell">import System.IO
s = "hello"
s = "hello"
s1 = s ++ " literal"
s1 = s ++ " literal"
main = do putStrLn (s ++ " literal")
main = do putStrLn (s ++ " literal")
putStrLn s1</lang>
putStrLn s1</syntaxhighlight>

=={{header|HicEst}}==
<syntaxhighlight lang="hicest">CHARACTER s = "hello", sl*100

WRITE() s // " literal"
sl = s // " literal"
WRITE() sl</syntaxhighlight>

=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">procedure main()
s1 := "hello"
write(s2 := s1 || " there.") # capture the reuslt for
write(s2) # ... the 2nd write
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
<syntaxhighlight lang="idl">s1='Hello'
<lang idl>
s1='Hello'
print, s1 + ' literal'
print, s1 + ' literal'
s2=s1 + ' literal'
s2=s1 + ' literal'
print, s2
print, s2</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
<lang J> s1 =. 'Some '
<syntaxhighlight lang="j"> s1 =. 'Some '
]s1, 'text '
]s1, 'text '
Some text
Some text
]s2 =. s1 , 'more text!'
]s2 =. s1 , 'more text!'
Some more text!</lang>
Some more text!</syntaxhighlight>
For more info see:
For more info see:
http://www.jsoftware.com/help/dictionary/d320.htm on ,
* http://www.jsoftware.com/help/dictionary/d320.htm on <code>,</code>
http://www.jsoftware.com/help/dictionary/d500.htm on ]
* http://www.jsoftware.com/help/dictionary/d500.htm on <code>]</code>


=={{header|Java}}==
=={{header|Java}}==
There are multiple ways to concatenate string values in Java.<br />
<lang java5>public class Str{
The most common way is through the plus operator.
<syntaxhighlight lang="java">
String string = "abc" + "def";
</syntaxhighlight>
Which can also be written as
<syntaxhighlight lang="java">
String string = "abc";
string += "def";
</syntaxhighlight>
There is also the ''String.concat'' method
<syntaxhighlight lang="java">
String string = "abc".concat("def");
</syntaxhighlight>
You could use a ''StringBuilder'' object if you're appending multiple strings.
<syntaxhighlight lang="java">
StringBuilder string = new StringBuilder();
string.append("abc").append("def");
</syntaxhighlight>
''StringBuilder'' also conveniently lets you insert strings within strings.<br />
So, you can also concatenate a string as follows
<syntaxhighlight lang="java">
StringBuilder string = new StringBuilder();
string.append("abc");
string.insert(3, "def");
</syntaxhighlight>
A less common approach would be to use the ''String.format'' or ''String.formatted'' methods.
<syntaxhighlight lang="java">
String string = String.format("%s%s", "abc", "def");
</syntaxhighlight>
<syntaxhighlight lang="java">
String string = "%s%s".formatted("abc", "def");
</syntaxhighlight>
All of these methods will produce the following string
<pre>
abcdef
</pre>
<br />
Alternately
<syntaxhighlight lang="java5">public class Str{
public static void main(String[] args){
public static void main(String[] args){
String s = "hello";
String s = "hello";
Line 218: Line 1,239:
System.out.println(s2);
System.out.println(s2);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
Output:
<pre>hello literal
<pre>hello literal
hello literal</pre>
hello literal</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>var s = "hello"
<syntaxhighlight lang="javascript">var s = "hello"
print(s + " there!")</lang>
print(s + " there!")</syntaxhighlight>

=={{header|Joy}}==
<syntaxhighlight lang="joy">
"title:" " text" concat.</syntaxhighlight>
{{out}}
<pre>"title: text"</pre>

=={{header|jq}}==
<syntaxhighlight lang="jq">"hello" as $s | $s + " there!"</syntaxhighlight>
{{Out}}
# Use the -r command-line option if you wish
# to suppress the string quotation marks
hello there!

=={{header|Julia}}==
<syntaxhighlight lang="julia">s = "hello"
println(s * " there!")</syntaxhighlight>

=={{header|K}}==
Translation of <b>J</b> code:
<syntaxhighlight lang="k">
s1: "Some "
s1, "text "
s2: s1 , "more text!"
</syntaxhighlight>
{{out}}
<pre>
"Some "
"Some text"
"Some more text!"
</pre>

=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">fun main() {
val s1 = "James"
val s2 = "Bond"
println(s1)
println(s2)
val s3 = s1 + " " + s2
println(s3)
}</syntaxhighlight>
{{Out}}
<pre>James
Bond
James Bond</pre>

=={{header|LabVIEW}}==
The two input on the left are String Controls, the output on the right is a String Indicator. All of them can be placed on the Front Panel.
The Concatenate Strings function can be placed on the Block Diagram.
You can switch between the Front Panel and the Block Diagram by pressing Ctrl+E.

[[File:LV_strcat.png]]

=={{header|Lambdatalk}}==
In Lambdatalk writing {def name a sequence of words} replaces the sequence of words by the given name in the code string. The name is a word and is not evaluated. Bracketing a name between two curly braces returns its related value. And concatenating named strings is simply done by writing names between curly braces and separated by spaces.
<syntaxhighlight lang="scheme">
{def christian_name Albert}
-> christian_name
{def name de Jeumont-Schneidre}
-> name

{christian_name} {name}
-> Albert de Jeumont-Schneidre
</syntaxhighlight>

=={{header|Lang}}==
<syntaxhighlight lang="lang">
$s1 = hello
$s2 = \sworld

fn.println($s1 world)
# Output: hello world

fn.println($s1$s2)
# Output: hello world

fn.println(fn.concat($s1, $s2))
# Output: hello world

fn.println(parser.op($s1 ||| $s2))
# Output: hello world

fn.println(fn.add($s1, $s2))
# Output: hello world

fn.println(parser.op($s1 + $s2))
# Output: hello world
</syntaxhighlight>

=={{header|Lang5}}==
<syntaxhighlight lang="lang5">: concat 2 compress "" join ;
'hello " literal" concat</syntaxhighlight>

=={{header|Lasso}}==
<syntaxhighlight lang="lasso">local(x = 'Hello')
local(y = #x + ', World!')
#x // Hello
#y // Hello, World!</syntaxhighlight>

=={{header|Liberty BASIC}}==
See [[#BASIC|BASIC]].

=={{header|Lingo}}==
<syntaxhighlight lang="lingo">a = "Hello"
b = a & " world!"
put b
-- "Hello world!"</syntaxhighlight>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>Section Header
<syntaxhighlight lang="lisaac">Section Header


+ name := STRING_CONCATENATION;
+ name := STRING_CONCATENATION;
Line 239: Line 1,367:


sc := "Hello";
sc := "Hello";
(sc + " literal").print;
(sc + " literal").println;

'\n'.print;
sv := sc + " literal";
sv := sc + " literal";
sv.print;
sv.println;

'\n'.print;
);</lang>
);</syntaxhighlight>

=={{header|LiveCode}}==
<syntaxhighlight lang="livecode">local str="live"
put str & "code" into str2
put str && str2</syntaxhighlight>
Output<pre>live livecode</pre>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>make "s "hello
<syntaxhighlight lang="logo">make "s "hello
print word :s "| there!|</lang>
print word :s "| there!|</syntaxhighlight>

=={{header|lua}}==
=={{header|Lua}}==
<lang lua>
a, = "hello "
<syntaxhighlight lang="lua">a = "hello "
print(a .. "world")
print(a .. "world")
c = a .. "world"
c = a .. "world"
print(c)</lang>
print(c)</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|M2000 Interpreter}}==
M2000 Environment is an application written in Visual Basic 6, so can use strings UTF16LE (max 2GByte), and Ansi strings. So here is an example which add two Ansi strings. To print them to console we have to convert to UTF16LE. We can use ansi strings for files and for buffers (memory blocks). Conversion use Locale (so Locale 1032 can be used for Greek Ansi codepage)
<lang objc>#import <Foundation/Foundation.h>


A memory word is two bytes.
int main()

{
<syntaxhighlight lang="m2000 interpreter">
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Module CheckString {
NSString *s = @"hello";
s$ = "hello"
printf("%s%s\n", [s UTF8String], " literal");
PRINT s$;" literal" 'or s$ + " literal"
NSString *s2 = [s stringByAppendingString:@" literal"];
s2$ = s$ + " literal"
PRINT s2$
// or, NSString *s2 = [NSString stringWithFormat:@"%@%@", s, @" literal"];
Print Len(s2$)=13
puts([s2 UTF8String]);
\\ get an ansi string
/* or */
k$=Str$("Hello")
NSMutableString *s3 = [NSMutableString stringWithString: s];
Print Len(k$)=2.5 ' 2.5 words or 5 bytes
[s3 appendString: @" literal"];
Print Chr$(k$)
puts([s3 UTF8String]);
k2$=k$+Str$(" literal")
Print Len(k2$)=6.5 ' 13 bytes
[pool release];
Print Chr$(k2$)
return 0;
Print Len(Chr$(k2$))=13 ' words
}</lang>
}
CheckString
</syntaxhighlight>


=={{header|M4}}==
=={{header|M4}}==
M4 has macros rather than variables, but a macro expanded can work like a variable.
M4 has macros rather than variables, but a macro expanded can work like a variable.
<lang m4>define(`concat',`$1$2')dnl
<syntaxhighlight lang="m4">define(`concat',`$1$2')dnl
define(`A',`any text value')dnl
define(`A',`any text value')dnl
concat(`A',` concatenated with string literal')
concat(`A',` concatenated with string literal')
define(`B',`concat(`A',` and string literal')')dnl
define(`B',`concat(`A',` and string literal')')dnl
B</lang>
B</syntaxhighlight>

=={{header|Maple}}==
<syntaxhighlight lang="maple">str := "Hello":
newstr := cat(str,", world!"):
str;
newstr;</syntaxhighlight>
{{out}}
<pre>
"Hello"
"Hello, world!"
</pre>

=={{header|Mathcad}}==
Uses Mathcad's built-in concat function to join the contents of a (string) variable to a string literal.
Both equations and text are typed directly onto, and evaluated on, a Mathcad worksheet.

[https://community.ptc.com/t5/PTC-Mathcad/Rosetta-Code-String-Concatenation/m-p/665044#M190096]

----
Define (:=) and display (=) the (string) variable Carpenter

Carpenter := "Gort. " (Carpenter = "Gort. ")

Define (:=) and display (=) the (string) variable Helen concatenated with a string literal.

Helen := concat(Carpenter,"Klaatu barada nikto."
Helen = "Gort. Klaatu barada nikto."
----

=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">str= "Hello ";
str<>"Literal"</syntaxhighlight>

=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">>> string1 = '1 Fish'

string1 =

1 Fish

>> string2 = [string1 ', 2 Fish, Red Fish, Blue Fish']

string2 =

1 Fish, 2 Fish, Red Fish, Blue Fish</syntaxhighlight>

=={{header|Maxima}}==
<syntaxhighlight lang="maxima">s: "the quick brown fox";
t: "jumps over the lazy dog";
sconcat(s, " ", t);
/* "the quick brown fox jumps over the lazy dog" */</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>s = "hello"
<syntaxhighlight lang="maxscript">s = "hello"
print (s + " literal")
print (s + " literal")
s1 = s + " literal"
s1 = s + " literal"
print s1</lang>
print s1</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Mercury}}==
<syntaxhighlight lang="mercury">:- module string_concat.
:- interface.


:- import_module io.
<lang metafont>string a, b;
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module string.

main(!IO) :-
S = "hello",
S1 = S ++ " world",
io.write_string(S, !IO), io.nl(!IO),
io.write_string(S1, !IO), io.nl(!IO).</syntaxhighlight>

=={{header|Metafont}}==
<syntaxhighlight lang="metafont">string a, b;
a := "String";
a := "String";
message a & " literal";
message a & " literal";
b := a & " literal";
b := a & " literal";
message b;</lang>
message b;</syntaxhighlight>

=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">"butter" :a
(a "scotch")=> "" join :b
a puts!
b puts!</syntaxhighlight>
{{out}}
<pre>
butter
butterscotch
</pre>

=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">s = "hello"
print s + " world!"</syntaxhighlight>

{{output}}
<pre>hello world!</pre>

=={{header|MIPS Assembly}}==
Using the following implementation of [[C]]'s <code>strcpy()</code>, we can concatenate strings easily by copying them to a RAM buffer back-to-back. We'll only do a few so that we don't clobber any other RAM we're using.

<syntaxhighlight lang="mips">main:
la $a0,String1
la $a1,UserRam

jal strcpy
nop

la $a0,String2
jal strcpy
nop
la $a0,UserRam
jal PrintString
nop

shutdown:
nop ;normally not needed, but Project 64 will throw an exception if I don't have a nop here.
b shutdown ;loop forever
nop
strcpy:
LBU t0,(a0)
nop
beqz t0,strcpy_done
SB t0,(a1) ;branch delay slot - this is actually executed BEFORE the beqz!
addiu a0,a0,1
b strcpy
addiu a1,a1,1 ;branch delay slot
strcpy_done:
jr ra
nop

String1:
.ascii "abcdefghijk"
.byte 0
.align 4
String2:
.ascii "lmnopqrstuvwxyz"
.byte 0
.align 4</syntaxhighlight>
{{out}}
<pre>abcdefghijklmnopqrstuvwxyz</pre>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Strings in Modula-3 are called <code>TEXT</code>s. Concatenation can use <code>&</code>, just like [[Ada]].
Strings in Modula-3 are called <code>TEXT</code>s. Concatenation can use <code>&</code>, just like [[Ada]].
<lang modula3>MODULE Concat EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Concat EXPORTS Main;


IMPORT IO;
IMPORT IO;
Line 312: Line 1,579:
string1 := string & " literal.\n";
string1 := string & " literal.\n";
IO.Put(string1);
IO.Put(string1);
END Concat.</lang>
END Concat.</syntaxhighlight>
Modula-3 also provides modules for dealing with <code>TEXT</code>s, such as <code>Text</code>.
Modula-3 also provides modules for dealing with <code>TEXT</code>s, such as <code>Text</code>.
<lang modula3>string1 := Text.Concat(string, " literal.\n");</lang>
<syntaxhighlight lang="modula3">string1 := Text.Concat(string, " literal.\n");</syntaxhighlight>

=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">STRCAT
SET S="STRING"
WRITE !,S
SET T=S_" LITERAL"
WRITE !,T
QUIT</syntaxhighlight>
{{out}}
<pre>
CACHE>D STRCAT^ROSETTA
STRING
STRING LITERAL
</pre>

=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">s1 = "hello"
println s1 + " world"

s2 = s1 + " world"
println s2</syntaxhighlight>
{{out}}
<pre>hello world
hello world</pre>

=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
String concatenation, in Neko
Tectonics:
nekoc string-concatenation.neko
neko string-concatenation [addon]
*/

var arg = $loader.args[0]
var addon
if arg != null addon = $string(arg)

var s = "abc"
$print("s: ", s, "\n")

var c = s + "def"
$print("c: ", c, "\n")

if arg != null {
c += addon
$print("addon: ", addon, "\n")
$print("c: ", c, "\n")
}</syntaxhighlight>

{{out}}
<pre>prompt$ nekoc string-concatenation.neko
prompt$ neko string-concatenation.n xyz
s: abc
c: abcdef
addon: xyz
c: abcdefxyz</pre>

=={{header|Nemerle}}==
Can be done with Concat() method or + operator:
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using Nemerle.Utility.NString; // contains method Concat()

module Stringcat
{
Main() : void
{
def text1 = "This string has";
def cat1 = Concat( " ", [text, "been concatenated"]);
def cat2 = text1 + " also been concatenated";
Write($"$cat1\n$cat2\n");
}
}</syntaxhighlight>

=={{header|NetRexx}}==
<syntaxhighlight lang="netrexx">/* NetRexx */

options replace format comments java crossref savelog symbols

s1 = 'any text value'
s2 = 'another string literal'
s3 = s1 s2 -- concatenate variables with blank space (note that only one blank space is added)
s4 = s1 || s2 -- concatenate variables with abuttal (here, no blank spaces are added)
s5 = s1 'another string literal' -- concatenate a variable and a literal with blank space
s6 = s1'another string literal' -- concatenate a variable and a literal using abuttal
s7 = s1 || 'another string literal' -- ditto

say 's1:' s1 -- concatenation with blank space is employed here too
say 's2:' s2
say 's3:' s3
say 's4:' s4
say 's5:' s5
say 's6:' s6
say 's7:' s7
</syntaxhighlight>
{{out}}
<pre>
s1: any text value
s2: another string literal
s3: any text value another string literal
s4: any text valueanother string literal
s5: any text value another string literal
s6: any text valueanother string literal
s7: any text valueanother string literal</pre>

=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">(let (str1 "foo")
(println str1)
(let (str2 (string str1 "bar"))
(println str2)))</syntaxhighlight>

=={{header|Nim}}==
Strings can be concatenated with <code>&</code>.
<syntaxhighlight lang="nim">let str = "String"
echo str & " literal."

# -> String literal.</syntaxhighlight>

Strings can be concatenated as arrays and joined with separating characters:
<syntaxhighlight lang="nim">import strutils
var str = "String"
echo join([str, " literal.", "HelloWorld!"], "~~")

# -> String~~ literal.~~HelloWorld!</syntaxhighlight>

Strings can be combined using string formatting:
<syntaxhighlight lang="nim">import strutils

var str = "String"
echo "$# $# $#" % [str, "literal.", "HelloWorld!"]
# -> String literal. HelloWorld!

# Alternate form providing automatic conversion of arguments to strings.
echo "$# $# $#".format(str, 123, "HelloWorld!")
# -> String 123 HelloWorld!</syntaxhighlight>

=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 STRING$="HELLO"
20 STRING$=STRING$+" WORLD!"
30 PRINT STRING$</syntaxhighlight>

=={{header|Objeck}}==
<syntaxhighlight lang="objeck">bundle Default {
class Repeat {
function : Main(args : String[]) ~ Nil {
s := "hello";
s->PrintLine();
" literal"->PrintLine();
s->Append(" literal");
s->PrintLine();
}
}
}</syntaxhighlight>

=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">MODULE Concat;

IMPORT Out,Strings;

VAR
S1:ARRAY 16 OF CHAR;
S2:ARRAY 8 OF CHAR;
PS1,PS2:POINTER TO ARRAY OF CHAR;
BEGIN
(* Static *)
S1 := "Hello ";
S2 := "literal";
Strings.Append(S2, S1);
Out.String(S1); Out.Ln;
(* Dynamic *)
NEW(PS1, 16);
NEW(PS2, 8);
COPY("Hello ", PS1^);
COPY("literal", PS2^);
Strings.Append(PS2^, PS1^);
Out.String(PS1^); Out.Ln;
END Concat.
</syntaxhighlight>

=={{header|Objective-C}}==
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>

int main()
{
@autoreleasepool {

NSString *s = @"hello";
printf("%s%s\n", [s UTF8String], " literal");
NSString *s2 = [s stringByAppendingString:@" literal"];
// or, NSString *s2 = [NSString stringWithFormat:@"%@%@", s, @" literal"];
puts([s2 UTF8String]);
/* or */
NSMutableString *s3 = [NSMutableString stringWithString: s];
[s3 appendString: @" literal"];
puts([s3 UTF8String]);
}
return 0;
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let s = "hello"
<syntaxhighlight lang="ocaml">let s = "hello"
let s1 = s ^ " literal"
let s1 = s ^ " literal"
let () =
let () =
print_endline (s ^ " literal");
print_endline (s ^ " literal");
print_endline s1</syntaxhighlight>
(* or Printf.printf "%s literal\n" s; *)

print_endline s1</lang>
=={{header|Oforth}}==

.s show the stack :
<syntaxhighlight lang="oforth">"Hello" dup " World!" + .s </syntaxhighlight>

{{out}}
<pre>
[1] (String) Hello World!
[2] (String) Hello
</pre>

=={{header|Openscad}}==
<syntaxhighlight lang="openscad">a="straw";
b="berry";
c=str(a,b); /* Concatenate a and b */
echo (c);</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
Strings are lists and are concatenated with the "Append" function. However, often "virtual strings" are used instead. [http://www.mozart-oz.org/home/doc/base/virtualstring.html "Virtual string are designed as a convenient way to combine strings, byte strings, atoms, integers and floats to compound strings without explicit concatenation and conversion"].
Strings are lists and are concatenated with the "Append" function. However, often "virtual strings" are used instead. [http://www.mozart-oz.org/home/doc/base/virtualstring.html "Virtual string are designed as a convenient way to combine strings, byte strings, atoms, integers and floats to compound strings without explicit concatenation and conversion"].
<syntaxhighlight lang="oz">declare

<lang oz>declare
S = "hello"
S = "hello"
{System.showInfo S#" literal"} %% virtual strings are constructed with "#"
{System.showInfo S#" literal"} %% virtual strings are constructed with "#"
S1 = {Append S " literal"}
S1 = {Append S " literal"}
{System.showInfo S1}
{System.showInfo S1}</syntaxhighlight>

</lang>
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">s = "Hello ";
s = Str(s, "world");
\\ Alternately, this could have been:
\\ s = concat(s, "world");
print(s);</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program StringConcat;
<syntaxhighlight lang="pascal">Program StringConcat;
Var
Var
s, s1 : String;
s, s1 : String;
Line 345: Line 1,834:
{ s1 := s + ' literal'; works too, with FreePascal }
{ s1 := s + ' literal'; works too, with FreePascal }
writeln(s1);
writeln(s1);
End.</lang>
End.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my $s = 'hello';
<syntaxhighlight lang="perl">my $s = 'hello';
print $s . ' literal', "\n";
print $s . ' literal', "\n";
my $s1 = $s . ' literal';
my $s1 = $s . ' literal';
print $s1, "\n";</lang>
print $s1, "\n";</syntaxhighlight>

An example of destructive concatenation:
An example of destructive concatenation:
<syntaxhighlight lang="perl">$s .= ' literal';
print $s, "\n";</syntaxhighlight>


=={{header|Phix}}==
<lang perl>$s .= ' literal';
{{libheader|Phix/basics}}
print $s, "\n";</lang>
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">string</span> <span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"at"</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s1</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s2</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"c"</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s1</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s2</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s3</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"s"</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s1</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s3</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s4</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"m"</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s1</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s4</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s5</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"The "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">&</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s3</span><span style="color: #0000FF;">&</span><span style="color: #008000;">" on the "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s4</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"."</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s5</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
"at"
"cat"
"sat"
"mat"
"The cat sat on the mat."
</pre>


=={{header|Perl 6}}==
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_concatenation
{{works with|Rakudo|#22 "Thousand Oaks"}}
by Galileo, 11/2022 #/


"Hello" " world" chain print nl
<lang perl6>my $s = 'hello';
say $s ~ ' literal';
my $s1 = $s ~ ' literal';
say $s1;</lang>


"Hello" var a
An example of destructive concatenation:
"world" var b
a print nl
b print nl
a " " b chain chain print
</syntaxhighlight>
{{out}}
<pre>Hello world
Hello
world
Hello world
=== Press any key to exit ===</pre>


=={{header|PHL}}==
<lang perl6>$s ~= ' literal';
say $s;</lang>


<syntaxhighlight lang="text">module stringcat;
=={{header|PL/I}}==
<lang PL/I>
declare (s, t) character (20) varying;


extern printf;
s = 'hello from me';
display (s || ' to you.' );
t = s;
display (t || ' to you all.' );
</lang>


@Integer main [
=={{header|PowerShell}}==
var a = "hello";
<lang powershell>$s = "Hello"
var b = a + " literal";
Write-Host $s World.
printf("%s\n", b);


return 0;
# alternative, using variable expansion in strings
]</syntaxhighlight>
Write-Host "$s World."

$s2 = $s + " World."
Write-Host $s2</lang>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
$s = "hello";
$s = "hello";
echo $s . " literal" . "\n";
echo $s . " literal" . "\n";
$s1 = $s . " literal";
$s1 = $s . " literal";
echo $s1 . "\n";
echo $s1 . "\n";
?></lang>
?></syntaxhighlight>

=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
Hello = "Hello, ",
print(Hello ++ "world!" ++ "\n"),
String = Hello ++ "world!",
String := String ++ "\n",
print(String).</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(let Str1 "First text"
<syntaxhighlight lang="picolisp">(let Str1 "First text"
(prinl Str1 " literal")
(prinl Str1 " literal")
(let Str2 (pack Str1 " literal")
(let Str2 (pack Str1 " literal")
(prinl Str2) ) )</lang>
(prinl Str2) ) )</syntaxhighlight>

=={{header|Pike}}==
<syntaxhighlight lang="pike">
string hello = "hello ";
write(hello + "world" + "\n");
string all_of_it = hello + "world";
write(all_of_it + "\n");
</syntaxhighlight>
{{Out}}
<pre>
hello world
hello world
</pre>

=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">declare (s, t) character (30) varying;

s = 'hello from me';
display (s || ' to you.' );
t = s || ' to you all';
display (t);</syntaxhighlight>

=={{header|Plain English}}==
Strings (and other values) can be concatenated to strings with <code>then</code>.
<syntaxhighlight lang="plainenglish">To run:
Start up.
Put "hello" into a string.
Put the string then " world" into another string.
Write the string to the console.
Write the other string to the console.
Wait for the escape key.
Shut down.</syntaxhighlight>
{{out}}
<pre>
hello
hello world
</pre>

=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">$s = "Hello"
Write-Host $s World.

# alternative, using variable expansion in strings
Write-Host "$s World."

$s2 = $s + " World."
Write-Host $s2</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang="basic">
<lang PureBasic>OpenConsole()
If OpenConsole()
s$ = "hello"
PrintN( s$ + " literal")
s2$ = s$ + " literal"
PrintN(s2$)


Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
s$ = "hello"
Input()
PrintN( s$ + " literal")
CloseConsole()
s2$ = s$ + " literal"
EndIf</syntaxhighlight>
PrintN(s2$)


{{out}}
Repeat: Until Inkey() <> ""</lang>
<pre>
hello literal
hello literal
</pre>

This version uses the debugger versus outputting to the console. It
implements 'EnableExplicit' which is similar to VisuaBasic's 'Option Explicit' which means all variables must be declared. It also features the use of string variables WITHOUT the dollar-sign suffix '$' which is common in BASIC variants to indicate the string datatype:
<syntaxhighlight lang="basic">
EnableExplicit

Define.s s1, s2, s3

s1 = "Hello "
s2 = "World"
s3 = s1 + s2
Debug s3
s3 = s3 + "!"
Debug s3
</syntaxhighlight>

{{out}}
<pre>
Hello World
Hello World!
</pre>


=={{header|Python}}==
=={{header|Python}}==
<lang python>s = "hello"
<syntaxhighlight lang="python">s1 = "hello"
print s + " literal"
print s1 + " world"

s1 = s + " literal"
s2 = s1 + " world"
print s1</lang>
print s2</syntaxhighlight>
{{out}}
<pre>hello world
hello world</pre>
When concatenating many strings, it is more efficient to use the join method of a string object, which takes a list of strings to be joined. The string on which join is called is used as a separator.
<syntaxhighlight lang="python">s1 = "hello"
print ", ".join([s1, "world", "mom"])

s2 = ", ".join([s1, "world", "mom"])
print s2</syntaxhighlight>
{{out}}
<pre>hello, world, mom
hello, world, mom</pre>

=={{header|QB64}}==
<syntaxhighlight lang="qbasic">s1$ = "String"
s2$ = s1$ + " concatenation"
Print s1$
Print s2$</syntaxhighlight>
{{out}}
<pre>
String
String concatenation
</pre>

=={{header|Quackery}}==

<syntaxhighlight lang="quackery"> $ "A duck's quack"
$ " has no echo."
join
echo$</syntaxhighlight>

{{out}}

<pre>A duck's quack has no echo.</pre>


=={{header|R}}==
=={{header|R}}==
<lang R>hello <- "hello"
<syntaxhighlight lang="r">hello <- "hello"
paste(hello, "literal") # "hello literal"
paste(hello, "literal") # "hello literal"
hl <- paste(hello, "literal") #saves concatenates string to a new variable
hl <- paste(hello, "literal") #saves concatenates string to a new variable
paste("no", "spaces", "between", "words", sep="") # "nospacesbetweenwords"</lang>
paste("no", "spaces", "between", "words", sep="") # "nospacesbetweenwords"</syntaxhighlight>

=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(define hello "hello")
(displayln hello)

(define world (string-append hello " " "world" "!"))
(displayln world)

;outputs:
; hello
; hello world!</syntaxhighlight>

=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#22 "Thousand Oaks"}}
<syntaxhighlight lang="raku" line>my $s = 'hello';
say $s ~ ' literal';
my $s1 = $s ~ ' literal';
say $s1;

# or, using mutating concatenation:

$s ~= ' literal';
say $s;</syntaxhighlight>
Note also that most concatenation in Raku is done implicitly via interpolation.

=={{header|Raven}}==
<syntaxhighlight lang="raven"># Cat strings
"First string and " "second string" cat print

# Join
[ "First string" "second string" "third string" ] " and " join print

# print
[ "First string" "second string" "third string" ] each print

# Formatted print
"\n" "Third string" "Second string" "First string" "%s %s %s %s" print

# Heredoc
" - NOT!!" as $x
"This is the only way to do it%($x)s" print</syntaxhighlight>
{{out}}
<pre>First string and second string
First string and second string and third string
First stringsecond stringthird string
First string Second string Third string

This is the only way to do it - NOT!!</pre>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>s: "hello"
<syntaxhighlight lang="rebol">s: "hello"
print s1: rejoin [s " literal"]
print s1: rejoin [s " literal"]
print s1</lang>
print s1</syntaxhighlight>

=={{header|Red}}==
<syntaxhighlight lang="red">>>str1: "Hello"
>>str2: append str1 " World"
>> print str2
Hello World
>> print str1
Hello World</syntaxhighlight>

=={{header|ReScript}}==
<syntaxhighlight lang="rescript">let s1 = "hello"
let s2 = s1 ++ " literal"

Js.log(s1)
Js.log(s2)
</syntaxhighlight>
{{output}}
<pre>$ bsc sc.res > sc.js
$ node sc.js
hello
hello literal
</pre>

=={{header|Retro}}==
<syntaxhighlight lang="retro">
'hello_ 'literal s:append s:put</syntaxhighlight>

=={{header|REXX}}==
<syntaxhighlight lang="rexx">s = "hello"
say s "literal"
t = s "literal" /*whitespace between the two strings causes a space in the output.*/
say t
/*the above method works without spaces too.*/

genus= "straw"
say genus"berry" /*this outputs strawberry.*/
say genus || "berry" /*concatenation using a double-pipe does not cause spaces.*/</syntaxhighlight>

=={{header|Ring}}==
<syntaxhighlight lang="ring">
aString = "Welcome to the "
bString = "Ring Programming Language"

see astring + bString + nl
</syntaxhighlight>

=={{header|RPL}}==
This example showcases the 2 types of variables offered by RPL : temporary ones declared with <code>→</code> that disappear when the program ends, and persistent ones declared with the <code>STO</code> (for STOre) instruction.
≪ "Hello " → string1
≪ string1 " world" + 'string2' STO
string1 string2
{{works with|Halcyon Calc|4.2.7}}
{{out}}
<pre>
2: "Hello"
1: "Hello world"
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>s = "hello"
<syntaxhighlight lang="ruby">
puts s + " literal"
s = "hello"

s1 = s + " literal"
puts "#{s} template" #=> "hello template"
puts s1
# Variable s is intact
s1 << " another" # append to s1</lang>
puts s #=> "hello"

puts s + " literal" #=> "hello literal"
# Variable s is still the same
puts s #=> "hello"

# Mutating s variable:

s += " literal"
puts s #=> "hello literal"
s << " another" # append to s, use only when string literals are not frozen
puts s #=> "hello literal another"

s = "hello"
puts s.concat(" literal") #=> "hello literal"
puts s #=> "hello literal"
puts s.prepend("Alice said: ") #=> "Alice said: hello literal"
puts s #=> "Alice said: hello literal"

</syntaxhighlight>

=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
let s = "hello".to_owned();
println!("{}", s);
let s1 = s + " world";
println!("{}", s1);
}</syntaxhighlight>

=={{header|SAS}}==
<syntaxhighlight lang="sas">data _null_;
a="Hello,";
b="World!";
c=a !! " " !! b;
put c;
*Alternative using the catx function;
c=catx (" ", a, b);
put c;
run;</syntaxhighlight>

=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
main is
s ::= "hello";
#OUT + s + " literal\n";
s2 ::= s + " literal";
#OUT + s2 + "\n";
end;
end;</syntaxhighlight>

=={{header|S-BASIC}}==
<syntaxhighlight lang="basic">
rem - the + operator is used to concatenate strings

var s1, s2 = string

s1 = "Hello"
print s1 + ", world"

s2 = s1 + ", world"
print s2

end
</syntaxhighlight>
{{out}}
<pre>
Hello, world
Hello, world
</pre>


=={{header|Scala}}==
Evaluation in a Scala worksheet, to val f2 is an anonymous function assigned.
<syntaxhighlight lang="scala"> val s = "hello" //> s : String = hello
val s2 = s + " world" //> s2 : String = hello world
val f2 = () => " !" //> f2 : () => String = <function0>

println(s2 + f2()) //> hello world !</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define s "hello")
<syntaxhighlight lang="scheme">(define s "hello")
(display (string-append s " literal"))
(display (string-append s " literal"))
(newline)
(newline)
(define s1 (string-append s " literal"))
(define s1 (string-append s " literal"))
(display s1)
(display s1)
(newline)</lang>
(newline)</syntaxhighlight>

=={{header|Scilab}}==
<syntaxhighlight lang="text">s1="Hello"
s1+" world!"
s2=s1+" world"
s2
</syntaxhighlight>
{{out}}
<pre style="height:20ex> --> s1="Hello"
s1 =
Hello
-->s1+" world!"
ans =
Hello world!
-->s2=s1+" world!"
s2 =
Hello world!
-->s2
Hello world! </pre>

=={{header|sed}}==
There are no variables in ''sed'', just two distinct locations for storing a string: The "pattern space" and the "hold space".

The pattern space contains the current input line. With the <code>h</code> command, it is copied to the hold space. Then, the <code>s</code> command appends a string literal to the pattern space:
<syntaxhighlight lang="sed">h
s/$/String Literal/</syntaxhighlight>
If necessary, the content of both spaces could be exchanged by a final <code>x</code> command.

=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
local
var string: s is "hello";
var string: s2 is "";
begin
writeln(s <& " world");
s2 := s & " world";
writeln(s2);
end func;</syntaxhighlight>
{{out}}
<pre>
hello world
hello world
</pre>

=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var s = 'hello';
say s+' literal';
var s1 = s+' literal';
say s1;</syntaxhighlight>
An example of destructive concatenation:
<syntaxhighlight lang="ruby">s += ' literal';
say s;</syntaxhighlight>

=={{header|Simula}}==
<syntaxhighlight lang="simula">TEXT PROCEDURE concatenate(head, tail);
TEXT head, tail;
BEGIN TEXT c;
c :- blanks(head.length + tail.length);
c.sub(c.start, head.length) := head; ! putText(), anyone?;
c.sub(c.start + head.length, tail.length) := tail;
concatenate:- c;
END;

TEXT stringVariable, another;
stringVariable :- "head ";
another :- concatenate(stringVariable, "and tail");
OutText("stringVariable: """); OutText(stringVariable);
OutText(""", another: "); OutText(another); Outimage;</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>define: #s -> 'hello'.
<syntaxhighlight lang="slate">define: #s -> 'hello'.
inform: s ; ' literal'.
inform: s ; ' literal'.
define: #s1 -> (s ; ' literal').
define: #s1 -> (s ; ' literal').
inform: s1.</lang>
inform: s1.</syntaxhighlight>

=={{header|Slope}}==
<syntaxhighlight lang="slope">(define s1 "Hello")
(display (append s1 ", World!"))
</syntaxhighlight>

{{out}}
<pre>
Hello, World!
</pre>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
In Smalltalk "," (comma) is a binary message (virtual function) implemented by Collection (and therefore also understood by strings):
<lang smalltalk>|s s1| s := 'hello'.

<syntaxhighlight lang="smalltalk">|s s1| s := 'hello'.
(s,' literal') printNl.
(s,' literal') printNl.
s1 := s,' literal'.
s1 := s,' literal'.
s1 printNl.</lang>
s1 printNl.</syntaxhighlight>

=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol"> greet1 = "Hello, "
output = greet1
greet2 = greet1 "World!"
output = greet2
end</syntaxhighlight>

=={{header|Sparkling}}==
<syntaxhighlight lang="sparkling">let s1 = "Hello";
let s2 = " world!";
print(s1 .. s2); // prints "Hello world!"</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>val s = "hello"
<syntaxhighlight lang="sml">val s = "hello"
val s1 = s ^ " literal\n"
val s1 = s ^ " literal\n"
val () =
val () =
print (s ^ " literal\n");
print (s ^ " literal\n");
print s1</lang>
print s1</syntaxhighlight>

=={{header|Stata}}==
=== Stata string scalars ===
<syntaxhighlight lang="stata">sca a = "foo"
sca b = "bar"
sca c = a+b
di c
foobar</syntaxhighlight>

=== Mata ===
<syntaxhighlight lang="stata">a = "foo"
b = "bar"
c = a+b
c
foobar</syntaxhighlight>

=={{header|Swift}}==
<syntaxhighlight lang="swift">let s = "hello"
println(s + " literal")
let s1 = s + " literal"
println(s1)</syntaxhighlight>

=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
| concatenate a string

'The quick brown fox ' $s
+ 'jumped over the lazy moon.' $s
$s []

</syntaxhighlight>

{{out}}
<pre>
The quick brown fox jumped over the lazy moon.
</pre>

=={{header|Tailspin}}==
Tailspin has no operator for concatenating strings, you simply use interpolation instead
<syntaxhighlight lang="tailspin">
def a: 'Hello';
'$a;, World!' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Hello, World!
</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set s hello
<syntaxhighlight lang="tcl">set s hello
puts "$s there!"
puts "$s there!"
append s " there!"
append s " there!"
puts $s</lang>
puts $s</syntaxhighlight>
You can also just group the strings to concatenate together at the point where they are used, using Tcl's built-in syntactic concatenation:
You can also just group the strings to concatenate together at the point where they are used, using Tcl's built-in syntactic concatenation:
<lang tcl>set s "Hello "
<syntaxhighlight lang="tcl">set s "Hello "
set t "World"
set t "World"
set u "!"
set u "!"
puts $s$t$u ;# There is nothing special here about using puts; just an example</lang>
puts $s$t$u ;# There is nothing special here about using puts; just an example</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">"HELLO"→Str0
Str0+" WORLD!"→Str0</syntaxhighlight>
{{out}}
<pre>HELLO WORLD!</pre>


=={{header|TI-89 BASIC}}==
<lang ti89b>"aard" → sv
<syntaxhighlight lang="ti89b">"aard" → sv
Disp sv & "vark"
Disp sv & "vark"
sv & "wolf" → sv2</lang>
sv & "wolf" → sv2</syntaxhighlight>

=={{header|TorqueScript}}==
<syntaxhighlight lang="torque">%string = "Hello";
echo(%string);
%other = " world!";
echo(%other);
echo(%string @ %other);</syntaxhighlight>

=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd

MainModule: {
_start: (λ locals:
s1 "concat"
s2 (+ s1 "enation")
(lout "s1: " s1)
(lout "s2: " s2)
)
}</syntaxhighlight>
{{out}}
<pre>
s1: concat
s2: concatenation
</pre>

=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
s = "Hello "
print s, "literal"

s1 = CONCAT (s,"literal")
print s1</syntaxhighlight>
{{out}}
<pre>
Hello literal
Hello literal
</pre>

=={{header|uBasic/4tH}}==
<syntaxhighlight lang="uBasic/4tH">
s := "Hello"
t = Join(s, " world!")
Print Show (s), Show (t)</syntaxhighlight>
{{out}}
<pre>Hello Hello world!

0 OK, 0:61</pre>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}} {{works with|bash}}
<lang bash>s="hello"
<syntaxhighlight lang="sh">s="hello"
echo "$s literal"
echo "$s literal"
s1="$s literal" # This method only works with a space between the strings
s1="$s literal"
echo $s1</lang>
echo $s1

# To concatenate without the space we need squiggly brackets:
genus='straw'
fruit=${genus}berry # This outputs the word strawberry
echo $fruit</syntaxhighlight>


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
<lang bash>echo "hello"
<syntaxhighlight lang="bash">echo "hello"
| xargs -n1 -i echo {} literal</lang>
| xargs -n1 -i echo {} literal</syntaxhighlight>

=={{header|Ursa}}==
<syntaxhighlight lang="ursa">decl string s1 s2
# make s1 contain "hello "
set s1 "hello "

# set s2 to contain s1 and "world"
set s2 (+ s1 "world")

# outputs "hello world"
out s2 endl console</syntaxhighlight>

=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1

|0100 @on-reset ( -> )
;str3 ;str1 copy-str
;str3 ;str2 append-str
;str3 print-str
#0a .Console/write DEO
BRK

@print-str ( str* -: )
&loop ( -- )
LDAk .Console/write DEO
INC2 LDAk ?&loop
POP2 JMP2r

@copy-str ( dest* src* -: )
STH2
&loop ( -- )
LDAkr STH2k STAr INC2 LDAkr STHr INC2r ?&loop
POP2 POP2r JMP2r

@append-str ( dest* src* -: )
STH2 end-str STH2r copy-str JMP2r

@end-str ( str* -: str* )
!&inner
&loop ( -- )
INC2 &inner LDAk ?&loop
JMP2r

@str1 "Uxn 00
@str2 "tal 00
@str3</syntaxhighlight>

=={{header|Vala}}==
<syntaxhighlight lang="vala">void main() {
var s = "hello";
print(s);
print(" literal\n");
var s2 = s + " literal\n";
print(s2);
}</syntaxhighlight>

=={{header|VBA}}==

<syntaxhighlight lang="vb">
Option Explicit

Sub String_Concatenation()
Dim str1 As String, str2 As String

str1 = "Rosetta"
Debug.Print str1
Debug.Print str1 & " code!"
str2 = str1 & " code..."
Debug.Print str2 & " based on concatenation of : " & str1 & " and code..."
End Sub
</syntaxhighlight>
{{out}}
<pre>
Rosetta
Rosetta code!
Rosetta code... based on concatenation of : Rosetta and code...</pre>

=={{header|VBScript}}==
<syntaxhighlight lang="vb"> s1="Hello"
s2=s1 & " World!"
WScript.Echo s2 </syntaxhighlight>
{{out}}
<pre>
Hello World!
</pre>


=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
works the same as in VBA, see [[String_concatenation#VBA]]


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
'''Platform:''' [[.NET]]
'''Platform:''' [[.NET]]

{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<syntaxhighlight lang="vbnet">s = "Hello"

<lang vbnet>s = "Hello"
Console.WriteLine(s & " literal")
Console.WriteLine(s & " literal")
s1 = s + " literal"
s1 = s + " literal"
Console.WriteLine(s1)</lang>
Console.WriteLine(s1)</syntaxhighlight>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">s := 'hello'

println(s)
println(s+' literal')

s2:= s+ ' literal'

println(s2)</syntaxhighlight>
{{out}}
<pre>
hello
hello literal
hello literal
</pre>

=={{header|Wee Basic}}==
<syntaxhighlight lang="wee basic">let string1$="Hello "
let string2$="world!"
print 1 string1$+string2$
end</syntaxhighlight>

=={{header|Wren}}==
<syntaxhighlight lang="wren">var s = "Hello, "
var t = s + "world!"
System.print(s)
System.print(t)</syntaxhighlight>

{{out}}
<pre>
Hello,
Hello, world!
</pre>

=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func Concat(S1, S2, S3); \Concatenate strings: S3:= S1 + S2
char S1, S2, S3;
int C, I, J;
[I:= 0;
repeat C:= S1(I);
S3(I):= C & $7F; \remove MSb terminator from first string
I:= I+1;
until C >= $80;
J:= 0;
repeat C:= S2(J);
S3(I+J):= C;
J:= J+1;
until C >= $80;
return S3;
];

code Text=12;
char A, B, C(80);
[A:= "Hello";
B:= " World!";
Concat(A, B, C);
Text(0, C);
]</syntaxhighlight>

=={{header|Yorick}}==
<syntaxhighlight lang="yorick">var1 = "Hello";
var2 = var1 + ", world!";
write, var1;
write, var2;</syntaxhighlight>

=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");

const debug = std.debug;
const heap = std.heap;
const mem = std.mem;

test "string concatenation" {
const hello = "Hello,";

debug.warn("\n{}{}\n", .{ hello, " world!" });

// Method 1: Array concatenation
//
// This only works if the values are known at compile-time.
const hello_world_at_comptime = hello ++ " world!";

debug.warn("{}\n", .{hello_world_at_comptime});

// Method 2: std.mem.concat
var buf: [128]u8 = undefined;
const allocator = &heap.FixedBufferAllocator.init(&buf).allocator;

const hello_world_concatenated = try mem.concat(allocator, u8, &[_][]const u8{ hello, " world!" });

debug.warn("{}\n", .{hello_world_concatenated});

// Method 3: std.mem.join
const hello_world_joined = try mem.join(allocator, " ", &[_][]const u8{ hello, "world!" });

debug.warn("{}\n", .{hello_world_joined});
}</syntaxhighlight>

{{out}}
<pre>Test [1/1] test "string concatenation"...
Hello, world!
Hello, world!
Hello, world!
Hello, world!
All 1 tests passed.</pre>

=={{header|zkl}}==
<syntaxhighlight lang="zkl">var s="Hello";
s2:=s+", world!"; s2.println(); //-->Hello, world!
s3:=String(s," ",s2); s3.println(); //-->Hello Hello, world!</syntaxhighlight>


{{omit from|bc|No string operations in bc}}
{{omit from|dc|No string operations in dc}}
[[Wikipedia::https://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28string_functions%29#Concatenation]]

=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: string_concat
input: ['hello', 'literal']
output: 'hello literal'
</syntaxhighlight>

=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/String_concatenation.png String concatenation]

Latest revision as of 16:37, 3 May 2024

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

Task
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Create a string variable equal to any text value.

Create another string variable whose value is the original variable concatenated with another string literal.

To illustrate the operation, show the content of the variables.

Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

Translation of: Python
V s1 = ‘hello’
print(s1‘ world’)
V s2 = s1‘ world’
print(s2)
Output:
hello world
hello world

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program concatStr64.s   */
 
/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessFinal:   .asciz "The final string is \n"
 
szString:            .asciz "Hello "
szString1:           .asciz " the world. \n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
szFinalString:   .skip 255
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main:
                                   // load string 
    ldr x1,qAdrszString
    ldr x2,qAdrszFinalString
    mov x4,0
1:
    ldrb w0,[x1,x4]                // load byte of string
    strb w0,[x2,x4]
    cmp x0,0                       // compar with zero ?
    add x3,x4,1
    csel x4,x3,x4,ne               // if x0 <> 0 x4 = x4 +1 sinon x4
    bne 1b
    ldr x1,qAdrszString1
    mov x3,0
2:
    ldrb w0,[x1,x3]                // load byte of string 1
    strb w0,[x2,x4]
    cmp x0,0                       // compar with zero ?
    add x5,x4,1
    csel x4,x5,x4,ne
    add x5,x3,1
    csel x3,x5,x3,ne
    bne 2b
    mov x0,x2                      // display final string
    bl affichageMess
100:                               // standard end of the program */
    mov x0,0                       // return code
    mov x8,EXIT                    // request to exit program
    svc 0                          // perform the system call
qAdrszString:             .quad szString
qAdrszString1:            .quad szString1
qAdrszFinalString:        .quad szFinalString
qAdrszMessFinal:          .quad szMessFinal
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Output:
Hello  the world.

ABAP

DATA: s1 TYPE string,
      s2 TYPE string.

s1 = 'Hello'.
CONCATENATE s1 ' literal' INTO s2 RESPECTING BLANKS.
WRITE: / s1.
WRITE: / s2.
Output:
Hello
Hello literal

Another way

REPORT string_concatenation.

DATA(var1) = 'Hello'.
DATA(var2) = 'Literal'.

cl_demo_output=>new(
          )->begin_section( 'String concatenation using |{ }|'
          )->write( 'Statement: |{ var1 } { var2 }|'
          )->write( |{ var1 } { var2 }|
          )->begin_section( 'String concatenation with new string'
          )->write( 'Statement: |{ var1 } world!|'
          )->write( |{ var1 } world!|
          )->display( ).
Output:
Hello literal
Hello world!

Action!

PROC Append(CHAR ARRAY text,suffix)
  BYTE POINTER srcPtr,dstPtr
  BYTE len

  len=suffix(0)
  IF text(0)+len>255 THEN
    len=255-text(0)
  FI
  IF len THEN
    srcPtr=suffix+1
    dstPtr=text+text(0)+1
    MoveBlock(dstPtr,srcPtr,len)
    text(0)==+suffix(0)
  FI
RETURN

PROC Concatenate(CHAR ARRAY text,left,right)
  SCopy(text,left)
  Append(text,right)
RETURN

PROC TestConcatenate(CHAR ARRAY left,right)
  CHAR ARRAY text(256)

  Concatenate(text,left,right)
  PrintF("""%S""+""%S""=""%S""%E",left,right,text)
RETURN

PROC Main()
  TestConcatenate("Hello", " World!")
RETURN
Output:

Screenshot from Atari 8-bit computer

"Hello"+" World!"="Hello World!"

ActionScript

package
{
    public class Str
    {
        public static function main():void
        {
            var s:String = "hello";
            trace(s + " literal");
            var s2:String = s + " literal";
            trace(s2);
        }
    }
}

Ada

with Ada.Text_IO;  use Ada.Text_IO;

procedure String_Concatenation is
   S1 : constant String := "Hello";
   S2 : constant String := S1 & " literal";
begin
   Put_Line (S1);
   Put_Line (S2);
end String_Concatenation;
Sample output:
Hello
Hello literal

Aime

text s, v;

s = "Hello";
o_(s, "\n");
v = s + ", World!";
o_(v, "\n");
Output:
Hello
Hello, World!

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
STRING s := "hello";
print ((s + " literal", new line));
STRING s1 := s + " literal";
print ((s1, new line))
Output:
hello literal
hello literal

ALGOL-M

begin

comment
   The string concatenation operator is ||, and the   
   default string length is 10 characters unless a
   longer length (up to 255) is explicitly declared;

string(20) s1, s2;

s1 := "Hello";
write (s1 || ", world");

s2 := s1 || ", world";
write (s2);

end
Output:
Hello, world
Hello, world


Apex

String s1 = 'Hello ';
String s2 = 'Salesforce Developer!';

String s3 = s1+s2;

// Print output
System.debug(s3);
Output:
Hello Salesforce Developer!

AppleScript

try
    set endMsg to "world!"
    set totMsg to "Hello, " & endMsg
    display dialog totMsg
end try

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program strConcat.s   */

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall
/* Initialized data */
.data
szMessFinal:   .asciz "The final string is \n"

szString:            .asciz "Hello "
szString1:           .asciz " the world. \n"

/* UnInitialized data */
.bss 
szFinalString:   .skip 255

/*  code section */
.text
.global main 
main:
                                         @ load string 
    ldr r1,iAdrszString
	ldr r2,iAdrszFinalString
    mov r4,#0
1:
    ldrb r0,[r1,r4]                      @ load byte of string
    strb r0,[r2,r4]
    cmp r0,#0                            @ compar with zero ?
    addne r4,#1
    bne 1b
    ldr r1,iAdrszString1
    mov r3,#0
2:
    ldrb r0,[r1,r3]                      @ load byte of string 1
    strb r0,[r2,r4]
    cmp r0,#0                            @ compar with zero ?
    addne r4,#1
    addne r3,#1
    bne 2b
    mov r0,r2                            @ display final string
    bl affichageMess
100:                                     @ standard end of the program */
    mov r0, #0                           @ return code
    mov r7, #EXIT                        @ request to exit program
    svc 0                                @ perform the system call
iAdrszString:             .int szString
iAdrszString1:            .int szString1
iAdrszFinalString:       .int szFinalString
iAdrszMessFinal:          .int szMessFinal

/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers 
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index 
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop 
                                                @ so here r2 contains the length of the message 
    mov r1,r0                                   @ address message in r1 
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write" 
    svc #0                                      @ call systeme
    pop {r0,r1,r2,r7,lr}                        @ restaur des  2 registres
    bx lr                                       @ return

Arturo

str1: "Hello "
str2: "World"
 
print str1 ++ str2 ++ "!"
Output:
Hello World!

Asymptote

string s1 = "Hello";
write(s1 + " World!");
write(s1, " World!");
string s2 = s1 + " World!";
write(s2);

AutoHotkey

s := "hello"
Msgbox, %s%
s1 := s . "  literal" ;the . is optional
Msgbox, %s1%

AWK

The AWK concatenation operator is nothing.

BEGIN {
   s = "hello"
   print s " literal"
   s1 = s " literal"
   print s1
}

Axe

Lbl CONCAT
Copy(r₁,L₁,length(r₁))
Copy(r₂,L₁+length(r₁),length(r₂)+1)
L₁
Return

BASIC

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
Works with: BASIC256
Works with: Liberty BASIC
Works with: QB64
Works with: Run Basic
Works with: Yabasic
s$ = "hello"
print s$ + " literal"
s2$ = s$ + " literal"
print s$
print s2$
Output:
hello literal
hello
hello literal

Applesoft BASIC

A semicolon (;) is not the same as a concatenate operator (+), it is an instruction that works only on the PRINT statement to suppress newlines at the end of a literal or series of literals. For example, the instruction S$="HELLO";"LITERAL" would result in a syntax error.

10 S$ = "HELLO"
20 PRINT S$ + " LITERAL"
30 PRINT S$
40 S2$ = S$ + " LITERAL"
50 PRINT S2$
Output:
HELLO LITERAL
HELLO
HELLO LITERAL

BaCon

A$ = "hello"
PRINT A$," World" 

A2$ = A$ & " using & to concat World"
PRINT A2$

BBC BASIC

      stringvar1$ = "Hello,"
      stringvar2$ = stringvar1$ + " world!"
      PRINT "Variable 1 is """ stringvar1$ """"
      PRINT "Variable 2 is """ stringvar2$ """"
Output:
Variable 1 is "Hello,"
Variable 2 is "Hello, world!"

IS-BASIC

100 LET S$="Hello"
110 LET S$=S$&" world!"
120 PRINT S$

BASIC256

s1$ = "Hello"
print s1$; " World!"
print s1$ + " World!"
print s1$ & " World!"
s2$ = s1$;  " World!"
print s2$
s2$ = s1$ +  " World!"
print s2$
s2$ = s1$ &  " World!"
print s2$

Run BASIC

Works with: Liberty BASIC
s1$ = "Hello"
print s1$; " World!"
print s1$ + " World!"
s2$ = s1$;  " World!"
print s2$
s2$ = s1$ +  " World!"
print s2$

True BASIC

Works with: BASIC256
LET s1$ = "Hello"
PRINT s1$; " World!"
PRINT s1$ + " World!"
LET s2$ = s1$ & " World!"
PRINT s2$
END

uBasic/4tH

s = Dup("Hello")
Print Show(s); " World!"
Print Show(Join(s, " World!"))
t = Join(s, " World!")
Print Show(t)
End

Yabasic

Works with: Liberty BASIC
Works with: QB64
Works with: QBasic
Works with: Run BASIC
s1$ = "Hello"
print s1$, " World!"
print s1$ + " World!"
s2$ = s1$ + " World!"
print s2$

ZX Spectrum Basic

10 LET s$="Hello"
20 LET s$=s$+" World!"
30 PRINT s$

Batch File

set string=Hello
echo %string% World
set string2=%string% World
echo %string2%

Beef

using System;
namespace StringConcatenation
{
  class Program {
    static void Main() {
        String s = scope ("hello");
        Console.Write(s);
        Console.WriteLine(" literal");
        s.Append(" literal");
        Console.WriteLine(s);
    }
  }
}

BQN

(Join) will concatenate two strings together.

str  "Hello "
newstr  str  "world"
•Show newstr
"Hello world"

Bracmat

"Hello ":?var1 
& "World":?var2 
& str$(!var1 !var2):?var12 
& put$("var1=" !var1 ", var2=" !var2 ", var12=" !var12 "\n")
Output:
var1= Hello  , var2= World , var12= Hello World

Burlesque

blsq ) "Hello, ""world!"?+
"Hello, world!"

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *sconcat(const char *s1, const char *s2)
{
  char *s0 = malloc(strlen(s1)+strlen(s2)+1);
  strcpy(s0, s1);
  strcat(s0, s2);
  return s0;
}

int main()
{
   const char *s = "hello";
   char *s2;
   
   printf("%s literal\n", s);
   /* or */
   printf("%s%s\n", s, " literal");
   
   s2 = sconcat(s, " literal");
   puts(s2);
   free(s2);
}

C#

using System;

class Program {
    static void Main(string[] args) {
        var s = "hello";
        Console.Write(s);
        Console.WriteLine(" literal");
        var s2 = s + " literal";
        Console.WriteLine(s2);
    }
}

C++

#include <string>
#include <iostream>

int main() {
   std::string s = "hello";
   std::cout << s << " literal" << std::endl;
   std::string s2 = s + " literal";
   std::cout << s2 << std::endl;
   return 0;
}
Output:
hello literal
hello literal

ChucK

"Hello" => string A;
A + " World!" => string B;
<<< B >>>;
Output:
"Hello World!"

Clojure

(def a-str "abcd")
(println (str a-str "efgh"))

(def a-new-str (str a-str "efgh"))
(println a-new-str)

COBOL

With the STRING verb:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Concat.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  Str  PIC X(7) VALUE "Hello, ".
       01  Str2 PIC X(15).

       PROCEDURE DIVISION.
           DISPLAY "Str  : " Str
           STRING Str " World!" DELIMITED BY SIZE INTO Str2
           DISPLAY "Str2 : " Str2

           GOBACK
           .

Alternate method using the CONCATENATE intrinsic function:

       ...
       PROCEDURE DIVISION.
           DISPLAY "Str  : " Str
           MOVE FUNCTION CONCATENATE(Str, " World!") TO Str2
           DISPLAY "Str2 : " Str2

           GOBACK
           .

String literals can also be concatenated in the follwing ways:

*      *> Using a '&'.
       01  Long-Str-Val     PIC X(200) VALUE "Lorem ipsum dolor sit "
           & "amet, consectetuer adipiscing elit, sed diam nonummy "
           & "nibh euismod tincidunt ut laoreet dolore magna aliquam "
           & "erat volutpat.".

*      *> Using a '-' in column 7. Note the first two literals have no
*      *> closing quotes.
       01  Another-Long-Str PIC X(200) VALUE " Ut wisi enim ad minim 
      -    "veniam, quis nostrud exerci tation ullamcorper suscipit
      -    "lobortis nisl ut aliquip ex ea commodo consequat".

Common Lisp

(let ((s "hello"))
    (format t "~a there!~%" s)
    (let* ((s2 " there!")
           (s (concatenate 'string s s2)))
        (format t "~a~%" s)))
(defparameter *s* "hello")
(print (concatenate 'string *s* " literal"))
(defparameter *s1* (concatenate 'string *s* " literal"))
(print *s1*)

Component Pascal

BlackBox Component Builder

MODULE StringConcatenation;
IMPORT StdLog;

PROCEDURE Do*;
VAR
	str1,str2: ARRAY 128 OF CHAR;
BEGIN
	str1 := "Hello";
	str2 := str1 + " world";
	StdLog.String(":> " + str2);StdLog.Ln
END Do;

END StringConcatenation.

Execute: ^Q StringConcatenation.Do

Output:
:> Hello world

D

import std.stdio;
 
void main() {
    string s = "hello";
    writeln(s ~ " world");
    auto s2 = s ~ " world";
    writeln(s2);
}

DCL

$ string1 = "hello"
$ string2 = string1 + " world"
$ show symbol string*
Output:
  STRING1 = "hello"
  STRING2 = "hello world"

Delphi

program Concat;

{$APPTYPE CONSOLE}

var
  s1, s2: string;
begin
  s1 := 'Hello';
  s2 := s1 + ' literal';
  WriteLn(s1);
  WriteLn(s2);
end.

DWScript

var s1 := 'Hello';
var s2 := s1 + ' World';

PrintLn(s1);
PrintLn(s2);

Dyalect

Translation of: Swift
var s = "hello"
print(s + " literal")
var s1 = s + " literal"
print(s1)

Dylan.NET

//to be compiled using dylan.NET v. 11.5.1.2 or later.
#refstdasm mscorlib.dll

import System

assembly concatex exe
ver 1.3.0.0

class public Program

   method public static void main()
        var s as string = "hello"
        Console::Write(s)
        Console::WriteLine(" literal")
        var s2 as string = s + " literal"
        Console::WriteLine(s2)
  end method

end class

Déjà Vu

local :s1 "hello"
local :s2 concat( s1 ", world" )
!print s2
Output:
hello, world

EasyLang

a$ = "hello"
b$ = a$ & " world"
print b$

Ecstasy

module StringAppend {
    void run() {
        String start  = "hello";
        String finish = " world";

        // approach #1: add strings together
        String approach1 = start + finish;

        // approach #2: StringBuffer
        String approach2 = new StringBuffer()
                .append(start)
                .append(finish)
                .toString();

        // approach #3: string template
        String approach3 = $"{start}{finish}";

        @Inject Console console;
        console.print($|
                       |Appending strings:
                       |
                       |  {start=}
                       |  {finish=}
                       |
                       |  {approach1=}
                       |  {approach2=}
                       |  {approach3=}
                       |
                     );
    }
}
Output:
x$ xec doc/examples/StringAppend

Appending strings:

  start=hello
  finish= world

  approach1=hello world
  approach2=hello world
  approach3=hello world

Ela

Strings in Ela support a polymorphic concatenation operator (++):

hello = "Hello"
hello'world = hello ++ ", " ++ "world"
(hello, hello'world)
Output:
("Hello", "Hello, world!")

However, as long as strings in Ela are indexed arrays, this operator is not very effective for a large number of concatenations. Therefore one can use an alternate technique (a pure StringBuilder type defined in standard prelude). The resulting code would look like so:

toString $ "Hello" +> ", " +> "world"

The (+>) token is a type constructor. Therefore the result of its application is an instance of type StringBuilder. In order to produce a string one should call a polymorphic toString function at the end as shown above.

Elena

ELENA 6.x:

public program()
{
    var s := "Hello";
    var s2 := s + " literal";
 
    console.writeLine(s);
    console.writeLine(s2);
    console.readChar()
}
Output:
Hello
Hello literal

EMal

text s = "hello"
write(s)
writeLine(" literal")
text s2 = s + " literal"
writeLine(s2)
Output:
hello literal
hello literal

Elixir

s = "hello"
t = s <> " literal"

IO.puts s
IO.puts t
Output:
hello
hello literal

Emacs Lisp

(defvar foo "foo")
(defvar foobar (concat foo "bar"))
(message "%sbar" foo) 
(message "%s" foobar)
Output:
foobar
foobar

Erlang

S = "hello",
S1 = S ++ " literal",
io:format ("~s literal~n",[S]),
io:format ("~s~n",[S1])
Sample output:
hello literal
hello literal

ERRE

  ..........
  S$="HELLO"
  PRINT(S$;" LITERAL") ! or S$+" LITERAL"
  S2$=S$+" LITERAL"
  PRINT(S2$)
  ..........

Euphoria

sequence s, s1
s = "hello"
puts(1, s & " literal")
puts(1,'\n')
s1 = s & " literal"
print (1, s1))
puts(1,'\n')
Output:
hello literal
hello literal

Excel

Take three cells, say A1,B1 and C1. In C1, type in :

=CONCATENATE(A1;" ";B1)

As the text in A1 and/or B1 is changed, C1 will be updated.

Hello	World	Hello World

F#

Translation of: C#
open System

[<EntryPoint>]
let main args =
    let s = "hello"
    Console.Write(s)
    Console.WriteLine(" literal")
    let s2 = s + " literal"
    Console.WriteLine(s2)
    0

Factor

"wake up" [ " sheeple" append print ] [ ", you sheep" append ] bi print

Falcon

'VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems falconic

/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */

s = "critical"
> s + " literal"
s2 = s + " literal"
> s2
Output:
critical literal
critical literal
[Finished in 0.2s]

Fantom

Illustrating in fansh:

fansh> a := "abc"
abc
fansh> b := a + "def"
abcdef
fansh> a
abc
fansh> b
abcdef
/* gary chike                        08/27/2023 */

class Main
{
    static Void main() {
        s1 := "Only The"
        s2 := "knows"
        s3 := s1 + " Fantom " + s2 + "!" // Concatenation
        echo(s3)
        s4 := "$s1 Fantom $s2!" // String interpolation
        echo(s4)
    }
}
Output:
Only The Fantom knows!
Only The Fantom knows!

Fe

pack is not a built-in function, see its definition here.

(print (pack '("Hello" " world!")))

Forth

Works with: GNU Forth
s" hello" pad place
pad count type
s"  there!" pad +place    \ +place is called "append" on some Forths
pad count type

Fortran

program StringConcatenation

integer, parameter          :: maxstringlength = 64
character (maxstringlength) :: s1, s = "hello"

print *,s // " literal"
s1 = trim(s) // " literal"
print *,s1

end program

FreeBASIC

' FB 1.05.0 Win64

Var s1 = "String"
Var s2 = s1 + " concatenation"
Print s1
Print s2
Sleep
Output:
String
String concatenation

Frink

a = "Frink"
b = a + " rules!"
println[b]

FutureBasic

window 1

CFStringRef s1, s2

s1 = @"any text value "
print s1

s2 = fn StringByAppendingString( s1, @"another string literal" )
print s2

HandleEvents

Gambas

In gambas, the ampersand symbol is used as a concatenation operator:

Click this link to run this code

Public sub main()
DIM bestclub AS String
DIM myconcat AS String

bestclub = "Liverpool"
myconcat = bestclub & " Football Club"

Print myconcat

End

GDScript

Works with: Godot version 4.0.1
extends MainLoop


func _process(_delta: float) -> bool:
	var first: String = "123"
	var second: String = first + "abc"

	print(first)
	print(second)

	return true # Exit

GlovePIE

var.text1="Hello, "
debug=var.text1+"world!"

Go

package main

import "fmt"

func main() {
    // text assigned to a string variable
    s := "hello"

    // output string variable
    fmt.Println(s)

    // this output requested by original task descrption, although
    // not really required by current wording of task description.
    fmt.Println(s + " literal")

    // concatenate variable and literal, assign result to another string variable
    s2 := s + " literal"

    // output second string variable
    fmt.Println(s2)
}
Output:
hello
hello literal
hello literal

Golfscript

"Greetings ":s;
s"Earthlings"+puts
s"Earthlings"+:s1;
s1 puts

Groovy

def s = "Greetings "
println s + "Earthlings"

def s1 = s + "Earthlings"
println s1
Output:
Greetings Earthlings
Greetings Earthlings

Halon

The dot (concatenation) operator may cast datatypes to strings.

echo "Hello" . "World " . 123;

Haskell

import System.IO
s = "hello"
s1 = s ++ " literal"
main = do putStrLn (s ++ " literal")
          putStrLn s1

HicEst

CHARACTER s = "hello", sl*100

WRITE() s // " literal"
sl = s // " literal"
WRITE() sl

Icon and Unicon

procedure main()
s1 := "hello"
write(s2 := s1 || " there.")  # capture the reuslt for 
write(s2)                     # ... the 2nd write
end

IDL

s1='Hello'
print, s1 + ' literal'
s2=s1 + ' literal'
print, s2

J

   s1 =. 'Some '
   ]s1, 'text '
Some text 
   ]s2 =. s1 , 'more text!'
Some more text!

For more info see:

Java

There are multiple ways to concatenate string values in Java.
The most common way is through the plus operator.

String string = "abc" + "def";

Which can also be written as

String string = "abc";
string += "def";

There is also the String.concat method

String string = "abc".concat("def");

You could use a StringBuilder object if you're appending multiple strings.

StringBuilder string = new StringBuilder();
string.append("abc").append("def");

StringBuilder also conveniently lets you insert strings within strings.
So, you can also concatenate a string as follows

StringBuilder string = new StringBuilder();
string.append("abc");
string.insert(3, "def");

A less common approach would be to use the String.format or String.formatted methods.

String string = String.format("%s%s", "abc", "def");
String string = "%s%s".formatted("abc", "def");

All of these methods will produce the following string

abcdef


Alternately

public class Str{
   public static void main(String[] args){
      String s = "hello";
      System.out.println(s + " literal");
      String s2 = s + " literal";
      System.out.println(s2);
   }
}
Output:
hello literal
hello literal

JavaScript

var s = "hello"
print(s + " there!")

Joy

"title:" " text" concat.
Output:
"title: text"

jq

"hello" as $s | $s + " there!"
Output:
# Use the -r command-line option if you wish 
# to suppress the string quotation marks
hello there!

Julia

s = "hello"
println(s * " there!")

K

Translation of J code:

s1: "Some "
s1, "text "
s2: s1 , "more text!"
Output:
"Some "
"Some text"
"Some more text!"

Kotlin

fun main() {
    val s1 = "James"
    val s2 = "Bond"
    println(s1)
    println(s2)
    val s3 = s1 + " " + s2
    println(s3)
}
Output:
James
Bond
James Bond

LabVIEW

The two input on the left are String Controls, the output on the right is a String Indicator. All of them can be placed on the Front Panel. The Concatenate Strings function can be placed on the Block Diagram. You can switch between the Front Panel and the Block Diagram by pressing Ctrl+E.

Lambdatalk

In Lambdatalk writing {def name a sequence of words} replaces the sequence of words by the given name in the code string. The name is a word and is not evaluated. Bracketing a name between two curly braces returns its related value. And concatenating named strings is simply done by writing names between curly braces and separated by spaces.

{def christian_name Albert}
-> christian_name
{def name de Jeumont-Schneidre}
-> name

{christian_name} {name}
-> Albert de Jeumont-Schneidre

Lang

$s1 = hello
$s2 = \sworld

fn.println($s1 world)
# Output: hello world

fn.println($s1$s2)
# Output: hello world

fn.println(fn.concat($s1, $s2))
# Output: hello world

fn.println(parser.op($s1 ||| $s2))
# Output: hello world

fn.println(fn.add($s1, $s2))
# Output: hello world

fn.println(parser.op($s1 + $s2))
# Output: hello world

Lang5

: concat  2 compress "" join ;
'hello " literal" concat

Lasso

local(x = 'Hello')
local(y = #x + ', World!')
#x // Hello
#y // Hello, World!

Liberty BASIC

See BASIC.

Lingo

a = "Hello"
b = a & " world!"
put b
-- "Hello world!"

Lisaac

Section Header

+ name := STRING_CONCATENATION;

Section Public

- main <- (
  + sc : STRING_CONSTANT;
  + sv : STRING;

  sc := "Hello";
  (sc + " literal").println;

  sv := sc + " literal";
  sv.println;

);

LiveCode

local str="live"
put str & "code" into str2
put str && str2

Output

live livecode

make "s "hello
print word :s "| there!|

Lua

a = "hello "
print(a .. "world")
c = a .. "world"
print(c)

M2000 Interpreter

M2000 Environment is an application written in Visual Basic 6, so can use strings UTF16LE (max 2GByte), and Ansi strings. So here is an example which add two Ansi strings. To print them to console we have to convert to UTF16LE. We can use ansi strings for files and for buffers (memory blocks). Conversion use Locale (so Locale 1032 can be used for Greek Ansi codepage)

A memory word is two bytes.

Module CheckString {
      s$ = "hello"
      PRINT s$;" literal" 'or s$ + " literal"
      s2$ = s$ + " literal"
      PRINT s2$
      Print Len(s2$)=13
      \\ get an ansi string
      k$=Str$("Hello")
      Print Len(k$)=2.5  ' 2.5 words or 5 bytes
      Print Chr$(k$)
      k2$=k$+Str$(" literal")
      Print Len(k2$)=6.5  ' 13 bytes
      Print Chr$(k2$)
      Print Len(Chr$(k2$))=13 ' words
}
CheckString

M4

M4 has macros rather than variables, but a macro expanded can work like a variable.

define(`concat',`$1$2')dnl
define(`A',`any text value')dnl
concat(`A',` concatenated with string literal')
define(`B',`concat(`A',` and string literal')')dnl
B

Maple

str := "Hello":
newstr := cat(str,", world!"):
str;
newstr;
Output:
                            "Hello"
                        "Hello, world!"

Mathcad

Uses Mathcad's built-in concat function to join the contents of a (string) variable to a string literal. Both equations and text are typed directly onto, and evaluated on, a Mathcad worksheet.

[1]


Define (:=) and display (=) the (string) variable Carpenter

   Carpenter := "Gort. " (Carpenter = "Gort. ")

Define (:=) and display (=) the (string) variable Helen concatenated with a string literal.

   Helen := concat(Carpenter,"Klaatu barada nikto."
   Helen = "Gort. Klaatu barada nikto."

Mathematica/Wolfram Language

str= "Hello ";
str<>"Literal"

MATLAB / Octave

>> string1 = '1 Fish'

string1 =

1 Fish

>> string2 = [string1 ', 2 Fish, Red Fish, Blue Fish'] 

string2 =

1 Fish, 2 Fish, Red Fish, Blue Fish

Maxima

s: "the quick brown fox";
t: "jumps over the lazy dog";
sconcat(s, " ", t);
/* "the quick brown fox jumps over the lazy dog" */

MAXScript

s = "hello"
print (s + " literal")
s1 = s + " literal"
print s1

Mercury

:- module string_concat.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module string.

main(!IO) :-
    S = "hello",
    S1 = S ++ " world",
    io.write_string(S, !IO), io.nl(!IO),
    io.write_string(S1, !IO), io.nl(!IO).

Metafont

string a, b;
a := "String";
message a & " literal";
b := a & " literal";
message b;

min

Works with: min version 0.19.3
"butter" :a
(a "scotch")=> "" join :b
a puts!
b puts!
Output:
butter
butterscotch

MiniScript

s = "hello"
print s + " world!"
Output:
hello world!

MIPS Assembly

Using the following implementation of C's strcpy(), we can concatenate strings easily by copying them to a RAM buffer back-to-back. We'll only do a few so that we don't clobber any other RAM we're using.

main:
	la $a0,String1
	la $a1,UserRam

	jal strcpy			
	nop

	la $a0,String2
	jal strcpy
	nop
	
	la $a0,UserRam
	jal PrintString
	nop

shutdown:
	nop           ;normally not needed, but Project 64 will throw an exception if I don't have a nop here.
	b shutdown    ;loop forever
	nop
strcpy:
	LBU t0,(a0)
        nop
	beqz t0,strcpy_done	
	SB t0,(a1)			;branch delay slot - this is actually executed BEFORE the beqz!
	addiu a0,a0,1
	b strcpy
	addiu a1,a1,1		        ;branch delay slot
strcpy_done:
	jr ra
	nop

String1:
	.ascii "abcdefghijk"
	.byte 0
	.align 4
String2:
	.ascii "lmnopqrstuvwxyz"
	.byte 0
	.align 4
Output:
abcdefghijklmnopqrstuvwxyz

Modula-3

Strings in Modula-3 are called TEXTs. Concatenation can use &, just like Ada.

MODULE Concat EXPORTS Main;

IMPORT IO;

VAR string: TEXT := "String";
    string1: TEXT;

BEGIN
  IO.Put(string & " literal.\n");
  string1 := string & " literal.\n";
  IO.Put(string1);
END Concat.

Modula-3 also provides modules for dealing with TEXTs, such as Text.

string1 := Text.Concat(string, " literal.\n");

MUMPS

STRCAT
 SET S="STRING"
 WRITE !,S
 SET T=S_" LITERAL"
 WRITE !,T
 QUIT
Output:
CACHE>D STRCAT^ROSETTA
 
STRING
STRING LITERAL

Nanoquery

s1 = "hello"
println s1 + " world"

s2 = s1 + " world"
println s2
Output:
hello world
hello world

Neko

/**
 String concatenation, in Neko
 Tectonics:
    nekoc string-concatenation.neko
    neko string-concatenation [addon]
*/

var arg = $loader.args[0]
var addon
if arg != null addon = $string(arg)

var s = "abc"
$print("s: ", s, "\n")

var c = s + "def"
$print("c: ", c, "\n")

if arg != null {
    c += addon
    $print("addon: ", addon, "\n")
    $print("c: ", c, "\n")
}
Output:
prompt$ nekoc string-concatenation.neko
prompt$ neko string-concatenation.n xyz
s: abc
c: abcdef
addon: xyz
c: abcdefxyz

Nemerle

Can be done with Concat() method or + operator:

using System;
using System.Console;
using Nemerle.Utility.NString; // contains method Concat()

module Stringcat
{
    Main() : void
    {
        def text1 = "This string has";
        def cat1  = Concat( " ", [text, "been concatenated"]);
        def cat2  = text1 + " also been concatenated";
        Write($"$cat1\n$cat2\n");
    }
}

NetRexx

/* NetRexx */

options replace format comments java crossref savelog symbols

s1 = 'any text value'
s2 = 'another string literal'
s3 = s1    s2 -- concatenate variables with blank space (note that only one blank space is added)
s4 = s1 || s2 -- concatenate variables with abuttal (here, no blank spaces are added)
s5 = s1    'another string literal' -- concatenate a variable and a literal with blank space
s6 = s1'another string literal'     -- concatenate a variable and a literal using abuttal
s7 = s1 || 'another string literal' -- ditto

say 's1:' s1 -- concatenation with blank space is employed here too
say 's2:' s2
say 's3:' s3
say 's4:' s4
say 's5:' s5
say 's6:' s6
say 's7:' s7
Output:
s1: any text value
s2: another string literal
s3: any text value another string literal
s4: any text valueanother string literal
s5: any text value another string literal
s6: any text valueanother string literal
s7: any text valueanother string literal

NewLISP

(let (str1 "foo")
     (println str1)
     (let (str2 (string str1 "bar"))
	  (println str2)))

Nim

Strings can be concatenated with &.

let str = "String"
echo str & " literal."

# -> String literal.

Strings can be concatenated as arrays and joined with separating characters:

import strutils
var str = "String"
echo join([str, " literal.", "HelloWorld!"], "~~")

# -> String~~ literal.~~HelloWorld!

Strings can be combined using string formatting:

import strutils

var str = "String"
echo "$# $# $#" % [str, "literal.", "HelloWorld!"]
# -> String literal. HelloWorld!

# Alternate form providing automatic conversion of arguments to strings.
echo "$# $# $#".format(str, 123, "HelloWorld!")
# -> String 123 HelloWorld!

NS-HUBASIC

10 STRING$="HELLO"
20 STRING$=STRING$+" WORLD!"
30 PRINT STRING$

Objeck

bundle Default {
  class Repeat {
    function : Main(args : String[]) ~ Nil {
      s := "hello";
      s->PrintLine();
      " literal"->PrintLine();
      s->Append(" literal");
      s->PrintLine();
    }
  }
}

Oberon-2

MODULE Concat;

IMPORT Out,Strings;

VAR
  S1:ARRAY 16 OF CHAR;
  S2:ARRAY 8 OF CHAR;
  PS1,PS2:POINTER TO ARRAY OF CHAR;
BEGIN
  (* Static *)
  S1 := "Hello ";
  S2 := "literal";
  Strings.Append(S2, S1);
  Out.String(S1); Out.Ln;
  (* Dynamic *)
  NEW(PS1, 16);
  NEW(PS2, 8);
  COPY("Hello ", PS1^);
  COPY("literal", PS2^);
  Strings.Append(PS2^, PS1^);
  Out.String(PS1^); Out.Ln;
END Concat.

Objective-C

#import <Foundation/Foundation.h>

int main()
{
  @autoreleasepool {

    NSString *s = @"hello";
    printf("%s%s\n", [s UTF8String], " literal");
  
    NSString *s2 = [s stringByAppendingString:@" literal"];
    // or, NSString *s2 = [NSString stringWithFormat:@"%@%@", s, @" literal"];
    puts([s2 UTF8String]);
    /* or */
    NSMutableString *s3 = [NSMutableString stringWithString: s];
    [s3 appendString: @" literal"];
    puts([s3 UTF8String]);
  
  }
  return 0;
}

OCaml

let s = "hello"
let s1 = s ^ " literal"
let () =
  print_endline (s ^ " literal");
  print_endline s1

Oforth

.s show the stack :

"Hello" dup " World!" + .s
Output:
[1] (String) Hello World!
[2] (String) Hello

Openscad

a="straw";
b="berry";
c=str(a,b);    /* Concatenate a and b */
echo (c);

Oz

Strings are lists and are concatenated with the "Append" function. However, often "virtual strings" are used instead. "Virtual string are designed as a convenient way to combine strings, byte strings, atoms, integers and floats to compound strings without explicit concatenation and conversion".

declare
S = "hello"
{System.showInfo S#" literal"} %% virtual strings are constructed with "#"
S1 = {Append S " literal"}
{System.showInfo S1}

PARI/GP

s = "Hello ";
s = Str(s, "world");
\\ Alternately, this could have been:
\\ s = concat(s, "world");
print(s);

Pascal

Program StringConcat;
  Var
     s, s1   : String;
  
Begin
    s := 'hello';
    writeln(s + ' literal');
    s1 := concat(s, ' literal');
    { s1 := s + ' literal'; works too, with FreePascal }
    writeln(s1);
End.

Perl

my $s = 'hello';
print $s . ' literal', "\n";
my $s1 = $s . ' literal';
print $s1, "\n";

An example of destructive concatenation:

$s .= ' literal';
print $s, "\n";

Phix

Library: Phix/basics
string s1 = "at"                                ?s1
string s2 = "c"&s1                              ?s2
string s3 = "s"&s1                              ?s3
string s4 = "m"&s1                              ?s4
string s5 = "The "&s2&" "&s3&" on the "&s4&"."  ?s5
Output:
"at"
"cat"
"sat"
"mat"
"The cat sat on the mat."

Phixmonti

/# Rosetta Code problem: https://rosettacode.org/wiki/String_concatenation
by Galileo, 11/2022 #/

"Hello" " world" chain print nl

"Hello" var a
"world" var b
a print nl
b print nl
a " " b chain chain print
Output:
Hello world
Hello
world
Hello world
=== Press any key to exit ===

PHL

module stringcat;

extern printf;

@Integer main [
    var a = "hello";
    var b = a + " literal";
    printf("%s\n", b);

    return 0;
]

PHP

<?php
$s = "hello";
echo $s . " literal" . "\n";
$s1 = $s . " literal";
echo $s1 . "\n";
?>

Picat

main =>
  Hello = "Hello, ",
  print(Hello ++ "world!" ++ "\n"),
  String = Hello ++ "world!",
  String := String ++ "\n",
  print(String).

PicoLisp

(let Str1 "First text"
   (prinl Str1 " literal")
   (let Str2 (pack Str1 " literal")
      (prinl Str2) ) )

Pike

string hello = "hello ";
write(hello + "world" + "\n");
string all_of_it = hello + "world";
write(all_of_it + "\n");
Output:
hello world
hello world

PL/I

declare (s, t) character (30) varying;

s = 'hello from me';
display (s || ' to you.' );
t = s || ' to you all';
display (t);

Plain English

Strings (and other values) can be concatenated to strings with then.

To run:
Start up.
Put "hello" into a string.
Put the string then " world" into another string.
Write the string to the console.
Write the other string to the console.
Wait for the escape key.
Shut down.
Output:
hello
hello world

PowerShell

$s = "Hello"
Write-Host $s World.

# alternative, using variable expansion in strings
Write-Host "$s World."

$s2 = $s + " World."
Write-Host $s2

PureBasic

If OpenConsole()
  s$ = "hello"
  PrintN( s$ + " literal")
  s2$ = s$ + " literal"
  PrintN(s2$)

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf
Output:
hello literal
hello literal

This version uses the debugger versus outputting to the console. It implements 'EnableExplicit' which is similar to VisuaBasic's 'Option Explicit' which means all variables must be declared. It also features the use of string variables WITHOUT the dollar-sign suffix '$' which is common in BASIC variants to indicate the string datatype:

EnableExplicit

Define.s   s1, s2, s3

s1 = "Hello "
s2 = "World"
s3 = s1 + s2  
Debug s3 
s3 = s3 + "!"
Debug s3
Output:
Hello World
Hello World!

Python

s1 = "hello"
print s1 + " world"

s2 = s1 + " world"
print s2
Output:
hello world
hello world

When concatenating many strings, it is more efficient to use the join method of a string object, which takes a list of strings to be joined. The string on which join is called is used as a separator.

s1 = "hello"
print ", ".join([s1, "world", "mom"])

s2 = ", ".join([s1, "world", "mom"])
print s2
Output:
hello, world, mom
hello, world, mom

QB64

s1$ = "String"
s2$ = s1$ + " concatenation"
Print s1$
Print s2$
Output:
String
String concatenation

Quackery

  $ "A duck's quack"
  $ " has no echo."
  join 
  echo$
Output:
A duck's quack has no echo.

R

hello <- "hello"
paste(hello, "literal") # "hello literal"
hl <- paste(hello, "literal") #saves concatenates string to a new variable
paste("no", "spaces", "between", "words", sep="") # "nospacesbetweenwords"

Racket

#lang racket
(define hello "hello")
(displayln hello)

(define world (string-append hello " " "world" "!"))
(displayln world)

;outputs:
;  hello
;  hello world!

Raku

(formerly Perl 6)

Works with: Rakudo version #22 "Thousand Oaks"
my $s = 'hello';
say $s ~ ' literal';
my $s1 = $s ~ ' literal';
say $s1;

# or, using mutating concatenation:

$s ~= ' literal';
say $s;

Note also that most concatenation in Raku is done implicitly via interpolation.

Raven

# Cat strings
"First string and " "second string" cat print

# Join
[ "First string" "second string" "third string" ] " and " join print

# print
[ "First string" "second string" "third string" ] each print

# Formatted print
"\n" "Third string" "Second string" "First string" "%s %s %s %s" print

# Heredoc
" - NOT!!" as $x
"This is the only way to do it%($x)s" print
Output:
First string and second string
First string and second string and third string
First stringsecond stringthird string
First string Second string Third string 

This is the only way to do it - NOT!!

REBOL

s: "hello"
print s1: rejoin [s " literal"]
print s1

Red

>>str1: "Hello"
>>str2: append str1 " World"
>> print str2
Hello World
>> print str1 
Hello World

ReScript

let s1 = "hello"
let s2 = s1 ++ " literal"

Js.log(s1)
Js.log(s2)
Output:
$ bsc sc.res > sc.js
$ node sc.js
hello
hello literal

Retro

'hello_  'literal s:append s:put

REXX

s = "hello"
say s "literal" 
t = s "literal"         /*whitespace between the two strings causes a space in the output.*/
say t
                        /*the above method works without spaces too.*/

genus= "straw"
say genus"berry"        /*this outputs strawberry.*/
say genus || "berry"    /*concatenation using a double-pipe does not cause spaces.*/

Ring

aString = "Welcome to the "
bString = "Ring Programming Language"

see astring + bString + nl

RPL

This example showcases the 2 types of variables offered by RPL : temporary ones declared with that disappear when the program ends, and persistent ones declared with the STO (for STOre) instruction.

≪ "Hello " → string1 
   ≪ string1 " world" + 'string2' STO
   string1 string2
≫
Works with: Halcyon Calc version 4.2.7
Output:
2: "Hello"
1: "Hello world"

Ruby

s = "hello"

puts "#{s} template"       #=> "hello template"
# Variable s is intact
puts s                     #=> "hello" 

puts s + " literal"        #=> "hello literal"
# Variable s is still the same
puts s                     #=> "hello"

# Mutating s variable:

s += " literal"
puts s                     #=> "hello literal"
s << " another" # append to s, use only when string literals are not frozen
puts s                     #=> "hello literal another"

s = "hello"
puts s.concat(" literal")  #=> "hello literal"
puts s                     #=> "hello literal"
puts s.prepend("Alice said: ")  #=> "Alice said: hello literal"
puts s                     #=> "Alice said: hello literal"

Rust

fn main() {
    let s = "hello".to_owned();
    println!("{}", s);
    
    let s1 = s + " world";
    println!("{}", s1);
}

SAS

data _null_;
   a="Hello,";
   b="World!";
   c=a !! " " !! b;
   put c;
   *Alternative using the catx function;
   c=catx (" ", a, b);
   put c;
run;

Sather

class MAIN is
  main is
    s ::= "hello";
    #OUT + s + " literal\n";
    s2 ::= s + " literal";
    #OUT + s2 + "\n";
  end;
end;

S-BASIC

rem - the + operator is used to concatenate strings

var s1, s2 = string

s1 = "Hello"
print s1 + ", world"

s2 = s1 + ", world"
print s2

end
Output:
Hello, world
Hello, world


Scala

Evaluation in a Scala worksheet, to val f2 is an anonymous function assigned.

  val s = "hello"                                 //> s  : String = hello
  val s2 = s + " world"                           //> s2  : String = hello world
  val f2 = () =>  " !"                            //> f2  : () => String = <function0>

  println(s2 + f2())                              //> hello world !

Scheme

(define s "hello")
(display (string-append s " literal"))
(newline)
(define s1 (string-append s " literal"))
(display s1)
(newline)

Scilab

s1="Hello"
s1+" world!"
s2=s1+" world"
s2
Output:
 --> s1="Hello"
 s1  =
 Hello   
 -->s1+" world!"
 ans  =
 Hello world!   
 -->s2=s1+" world!"
 s2  =
 Hello world!   
 -->s2
 Hello world!   

sed

There are no variables in sed, just two distinct locations for storing a string: The "pattern space" and the "hold space".

The pattern space contains the current input line. With the h command, it is copied to the hold space. Then, the s command appends a string literal to the pattern space:

h
s/$/String Literal/

If necessary, the content of both spaces could be exchanged by a final x command.

Seed7

$ include "seed7_05.s7i";
 
const proc: main is func
  local
    var string: s is "hello";
    var string: s2 is "";
  begin
    writeln(s <& " world");
    s2 := s & " world";
    writeln(s2);
  end func;
Output:
hello world
hello world

Sidef

var s = 'hello';
say s+' literal';
var s1 = s+' literal';
say s1;

An example of destructive concatenation:

s += ' literal';
say s;

Simula

TEXT PROCEDURE concatenate(head, tail);
    TEXT head, tail;
BEGIN TEXT c;
    c :- blanks(head.length + tail.length);
    c.sub(c.start, head.length) := head; ! putText(), anyone?;
    c.sub(c.start + head.length, tail.length) := tail;
    concatenate:- c;
END;

TEXT stringVariable, another;
stringVariable :- "head ";
another :- concatenate(stringVariable, "and tail");
OutText("stringVariable: """); OutText(stringVariable);
OutText(""", another: "); OutText(another); Outimage;

Slate

define: #s -> 'hello'.
inform: s ; ' literal'.
define: #s1 -> (s ; ' literal').
inform: s1.

Slope

(define s1 "Hello")
(display (append s1 ", World!"))
Output:
Hello, World!

Smalltalk

In Smalltalk "," (comma) is a binary message (virtual function) implemented by Collection (and therefore also understood by strings):

|s s1| s := 'hello'.
(s,' literal') printNl.
s1 := s,' literal'.
s1 printNl.

SNOBOL4

	greet1 = "Hello, "
	output = greet1
	greet2 = greet1 "World!"
	output = greet2
end

Sparkling

let s1 = "Hello";
let s2 = " world!";
print(s1 .. s2); // prints "Hello world!"

Standard ML

val s = "hello"
val s1 = s ^ " literal\n"
val () =
  print (s ^ " literal\n");
  print s1

Stata

Stata string scalars

sca a = "foo"
sca b = "bar"
sca c = a+b
di c
  foobar

Mata

a = "foo"
b = "bar"
c = a+b
c
  foobar

Swift

let s = "hello"
println(s + " literal")
let s1 = s + " literal"
println(s1)

Symsyn

| concatenate a string

 'The quick brown fox ' $s
 + 'jumped over the lazy moon.' $s
 $s []
Output:
The quick brown fox jumped over the lazy moon.

Tailspin

Tailspin has no operator for concatenating strings, you simply use interpolation instead

def a: 'Hello';
'$a;, World!' -> !OUT::write
Output:
Hello, World!

Tcl

set s hello
puts "$s there!"
append s " there!"
puts $s

You can also just group the strings to concatenate together at the point where they are used, using Tcl's built-in syntactic concatenation:

set s "Hello "
set t "World"
set u "!"
puts $s$t$u  ;# There is nothing special here about using puts; just an example

TI-83 BASIC

"HELLO"→Str0
Str0+" WORLD!"→Str0
Output:
HELLO WORLD!

TI-89 BASIC

"aard" → sv
Disp sv & "vark"
sv & "wolf" → sv2

TorqueScript

%string = "Hello";
echo(%string);
%other = " world!";
echo(%other);
echo(%string @ %other);

Transd

#lang transd

MainModule: {
	_start: (λ locals: 
        s1 "concat" 
        s2 (+ s1 "enation")
        (lout "s1: " s1)
        (lout "s2: " s2)
    )
}
Output:
s1: concat
s2: concatenation

TUSCRIPT

$$ MODE TUSCRIPT
s = "Hello "
print s, "literal"

s1 = CONCAT (s,"literal")
print s1
Output:
Hello literal
Hello literal 

uBasic/4tH

s := "Hello"
t = Join(s, " world!")
Print Show (s), Show (t)
Output:
Hello   Hello world!

0 OK, 0:61

UNIX Shell

Works with: Bourne Shell
Works with: bash
s="hello"
echo "$s literal"
s1="$s literal"    # This method only works with a space between the strings
echo $s1

# To concatenate without the space we need squiggly brackets:
genus='straw'
fruit=${genus}berry  # This outputs the word strawberry
echo $fruit

UnixPipes

echo "hello" 
 | xargs -n1 -i echo {} literal

Ursa

decl string s1 s2
# make s1 contain "hello "
set s1 "hello "

# set s2 to contain s1 and "world"
set s2 (+ s1 "world")

# outputs "hello world"
out s2 endl console

Uxntal

|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1

|0100 @on-reset ( -> )
    ;str3 ;str1 copy-str
    ;str3 ;str2 append-str
    ;str3 print-str
    #0a .Console/write DEO
    BRK

@print-str ( str* -: )
    &loop ( -- )
        LDAk .Console/write DEO
        INC2 LDAk ?&loop
    POP2 JMP2r

@copy-str ( dest* src* -: )
    STH2
    &loop ( -- )
        LDAkr STH2k STAr INC2 LDAkr STHr INC2r ?&loop
    POP2 POP2r JMP2r

@append-str ( dest* src* -: )
    STH2 end-str STH2r copy-str JMP2r

@end-str ( str* -: str* )
    !&inner
    &loop ( -- )
        INC2 &inner LDAk ?&loop
    JMP2r

@str1 "Uxn 00
@str2 "tal 00
@str3

Vala

void main() {
  var s = "hello";
  print(s);
  print(" literal\n");
  var s2 = s + " literal\n";
  print(s2);
}

VBA

Option Explicit

Sub String_Concatenation()
Dim str1 As String, str2 As String

    str1 = "Rosetta"
    Debug.Print str1
    Debug.Print str1 & " code!"
    str2 = str1 & " code..."
    Debug.Print str2 & " based on concatenation of : " & str1 & " and code..."
End Sub
Output:
Rosetta
Rosetta code!
Rosetta code... based on concatenation of : Rosetta and code...

VBScript

	s1="Hello"
	s2=s1 & " World!"
	WScript.Echo s2
Output:
Hello World!


Visual Basic

Works with: Visual Basic version VB6 Standard

works the same as in VBA, see String_concatenation#VBA

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+
s = "Hello"
Console.WriteLine(s & " literal")
s1 = s + " literal"
Console.WriteLine(s1)

V (Vlang)

s := 'hello'

println(s)
println(s+' literal')

s2:= s+ ' literal'

println(s2)
Output:
hello
hello literal
hello literal

Wee Basic

let string1$="Hello "
let string2$="world!"
print 1 string1$+string2$
end

Wren

var s = "Hello, "
var t = s + "world!"
System.print(s)
System.print(t)
Output:
Hello, 
Hello, world!

XPL0

func Concat(S1, S2, S3);        \Concatenate strings: S3:= S1 + S2
char S1, S2, S3;
int  C, I, J;
[I:= 0;
repeat  C:= S1(I);
        S3(I):= C & $7F;        \remove MSb terminator from first string
        I:= I+1;
until   C >= $80;
J:= 0;
repeat  C:= S2(J);
        S3(I+J):= C;
        J:= J+1;
until   C >= $80;
return S3;
];

code Text=12;
char A, B, C(80);
[A:= "Hello";
 B:= " World!";
Concat(A, B, C);
Text(0, C);
]

Yorick

var1 = "Hello";
var2 = var1 + ", world!";
write, var1;
write, var2;

Zig

const std = @import("std");

const debug = std.debug;
const heap = std.heap;
const mem = std.mem;

test "string concatenation" {
    const hello = "Hello,";

    debug.warn("\n{}{}\n", .{ hello, " world!" });

    // Method 1: Array concatenation
    //
    // This only works if the values are known at compile-time.
    const hello_world_at_comptime = hello ++ " world!";

    debug.warn("{}\n", .{hello_world_at_comptime});

    // Method 2: std.mem.concat
    var buf: [128]u8 = undefined;
    const allocator = &heap.FixedBufferAllocator.init(&buf).allocator;

    const hello_world_concatenated = try mem.concat(allocator, u8, &[_][]const u8{ hello, " world!" });

    debug.warn("{}\n", .{hello_world_concatenated});

    // Method 3: std.mem.join
    const hello_world_joined = try mem.join(allocator, " ", &[_][]const u8{ hello, "world!" });

    debug.warn("{}\n", .{hello_world_joined});
}
Output:
Test [1/1] test "string concatenation"...
Hello, world!
Hello, world!
Hello, world!
Hello, world!
All 1 tests passed.

zkl

var s="Hello";
s2:=s+", world!"; s2.println(); //-->Hello, world!
s3:=String(s," ",s2); s3.println(); //-->Hello Hello, world!

https://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28string_functions%29#ConcatenationProperty "Wikipedia" (as page type) with input value "https://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28string_functions%29#Concatenation" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

Zoea

program: string_concat
  input: ['hello', 'literal']
  output: 'hello literal'

Zoea Visual

String concatenation