Copy a string: Difference between revisions

From Rosetta Code
Content added Content deleted
imported>Tromp
(add string copy for BLC)
 
(17 intermediate revisions by 14 users not shown)
Line 17: Line 17:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>V src = ‘hello’
<syntaxhighlight lang="11l">V src = ‘hello’
V dst = copy(src)</lang>
V dst = copy(src)</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
To copy a string, we use an MVC (Move Character). To make a reference to a string, we use a LA (Load Address).
To copy a string, we use an MVC (Move Character). To make a reference to a string, we use a LA (Load Address).
<lang 360asm>* Duplicate a string
<syntaxhighlight lang="360asm">* Duplicate a string
MVC A,=CL64'Hello' a='Hello'
MVC A,=CL64'Hello' a='Hello'
MVC B,A b=a memory copy
MVC B,A b=a memory copy
Line 38: Line 38:
A DS CL64 a
A DS CL64 a
B DS CL64 b
B DS CL64 b
REFA DS A @a</lang>
REFA DS A @a</syntaxhighlight>
=={{header|6502 Assembly}}==
<syntaxhighlight lang="6502asm">source equ $10 ;$10 was chosen arbitrarily
source_hi equ source+1 ;the high byte MUST be after the low byte, otherwise this will not work.
dest equ $12
dest_hi equ dest+1

LDA #<MyString ;get the low byte of &MyString
STA source
LDA #>MyString ;get the high byte
STA source_hi ;we just created a "shallow reference" to an existing string.
;As it turns out, this is a necessary step to do a deep copy.

LDA #<RamBuffer
STA dest
LDA #>RamBuffer
STA dest_hi


strcpy:
;assumes that RamBuffer is big enough to hold the source string, and that the memory ranges do not overlap.
;if you've ever wondered why C's strcpy is considered "unsafe", this is why.

LDY #0
.again:
LDA (source),y
STA (dest),y
BEQ .done
INY
BNE .again ;exit after 256 bytes copied or the null terminator is reached, whichever occurs first.
RTS

MyString:
byte "hello",0
RamBuffer:
byte 0,0,0,0,0,0</syntaxhighlight>

=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
Making a reference to an existing string is simple. Just load its memory location into an address register.
Making a reference to an existing string is simple. Just load its memory location into an address register.
<lang 68000devpac>myString: DC.B "HELLO WORLD",0
<syntaxhighlight lang="68000devpac">myString: DC.B "HELLO WORLD",0
EVEN
EVEN


LEA myString,A3</lang>
LEA myString,A3</syntaxhighlight>


Copying a string involves a little more work:
Copying a string involves a little more work:
<lang 68000devpac>StringRam equ $100000
<syntaxhighlight lang="68000devpac">StringRam equ $100000


myString: DC.B "HELLO WORLD",0
myString: DC.B "HELLO WORLD",0
Line 62: Line 99:


Terminated: ;the null terminator is already stored along with the string itself, so we are done.
Terminated: ;the null terminator is already stored along with the string itself, so we are done.
;program ends here.</lang>
;program ends here.</syntaxhighlight>


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
Line 70: Line 107:
This technique is useful if you wish to create a struct/record that needs to be able to retrieve a string quickly. All you need to do is get a pointer to the desired string and store it in RAM.
This technique is useful if you wish to create a struct/record that needs to be able to retrieve a string quickly. All you need to do is get a pointer to the desired string and store it in RAM.


<lang asm>.model small
<syntaxhighlight lang="asm">.model small
.stack 1024
.stack 1024


Line 89: Line 126:


mov ax,4C00h
mov ax,4C00h
int 21h ;quit program and return to DOS</lang>
int 21h ;quit program and return to DOS</syntaxhighlight>


===Creating a "deep copy"===
===Creating a "deep copy"===
This method will actually make a byte-for-byte copy somewhere else in RAM.
This method will actually make a byte-for-byte copy somewhere else in RAM.


<lang asm>.model small
<syntaxhighlight lang="asm">.model small
.stack 1024
.stack 1024


Line 121: Line 158:


mov ax,4C00h
mov ax,4C00h
int 21h ;quit program and return to DOS</lang>
int 21h ;quit program and return to DOS</syntaxhighlight>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program copystr64.s */
/* program copystr64.s */
Line 188: Line 225:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>data: lv_string1 type string value 'Test',
<syntaxhighlight lang="abap">data: lv_string1 type string value 'Test',
lv_string2 type string.
lv_string2 type string.
lv_string2 = lv_string1.</lang>
lv_string2 = lv_string1.</syntaxhighlight>


===Inline Declaration===
===Inline Declaration===
{{works with|ABAP|7.4 Or above only}}
{{works with|ABAP|7.4 Or above only}}


<lang ABAP>DATA(string1) = |Test|.
<syntaxhighlight lang="abap">DATA(string1) = |Test|.
DATA(string2) = string1.</lang>
DATA(string2) = string1.</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
CHAR ARRAY str1,str2,str3(10)
CHAR ARRAY str1,str2,str3(10)
Line 219: Line 256:
PrintF("alias=%S%E",str2)
PrintF("alias=%S%E",str2)
PrintF(" copy=%S%E",str3)
PrintF(" copy=%S%E",str3)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Copy_a_string.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Copy_a_string.png Screenshot from Atari 8-bit computer]
Line 234: Line 271:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
Strings are immutable in ActionScript, and can safely be assigned with the assignment operator, much as they can in Java.[http://livedocs.adobe.com/flash/9.0/main/00000647.html]
Strings are immutable in ActionScript, and can safely be assigned with the assignment operator, much as they can in Java.[http://livedocs.adobe.com/flash/9.0/main/00000647.html]
<lang ActionScript>var str1:String = "Hello";
<syntaxhighlight lang="actionscript">var str1:String = "Hello";
var str2:String = str1;</lang>
var str2:String = str1;</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Line 245: Line 282:


===Fixed Length String Copying.===
===Fixed Length String Copying.===
<lang ada>Src : String := "Hello";
<syntaxhighlight lang="ada">Src : String := "Hello";
Dest : String := Src;</lang>
Dest : String := Src;</syntaxhighlight>
Ada provides the ability to manipulate slices of strings.
Ada provides the ability to manipulate slices of strings.
<lang ada>Src : String := "Rosetta Stone";
<syntaxhighlight lang="ada">Src : String := "Rosetta Stone";
Dest : String := Src(1..7); -- Assigns "Rosetta" to Dest
Dest : String := Src(1..7); -- Assigns "Rosetta" to Dest
Dest2 : String := Src(9..13); -- Assigns "Stone" to Dest2</lang>
Dest2 : String := Src(9..13); -- Assigns "Stone" to Dest2</syntaxhighlight>


===Bounded Length String Copying===
===Bounded Length String Copying===
<lang ada>-- Instantiate the generic package Ada.Strings.Bounded.Generic_Bounded_Length with a maximum length of 80 characters
<syntaxhighlight lang="ada">-- Instantiate the generic package Ada.Strings.Bounded.Generic_Bounded_Length with a maximum length of 80 characters
package Flexible_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
package Flexible_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
use Flexible_String;
use Flexible_String;


Src : Bounded_String := To_Bounded_String("Hello");
Src : Bounded_String := To_Bounded_String("Hello");
Dest : Bounded_String := Src;</lang>
Dest : Bounded_String := Src;</syntaxhighlight>
Ada Bounded_String type provides a number of functions for dealing with slices.
Ada Bounded_String type provides a number of functions for dealing with slices.


=== Unbounded Length String Copying===
=== Unbounded Length String Copying===
<lang ada>-- The package Ada.Strings.Unbounded contains the definition of the Unbounded_String type and all its methods
<syntaxhighlight lang="ada">-- The package Ada.Strings.Unbounded contains the definition of the Unbounded_String type and all its methods
Src : Unbounded_String := To_Unbounded_String("Hello");
Src : Unbounded_String := To_Unbounded_String("Hello");
Dest : Unbounded_String := Src;</lang>
Dest : Unbounded_String := Src;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
Line 271: Line 308:


Copying an intrinsic string:
Copying an intrinsic string:
<lang aime>text s, t;
<syntaxhighlight lang="aime">text s, t;
t = "Rosetta";
t = "Rosetta";
s = t;</lang>
s = t;</syntaxhighlight>
Data of the non intrinsic byte array type can be referred more than once.
Data of the non intrinsic byte array type can be referred more than once.
Copying a binary array of bytes:
Copying a binary array of bytes:
<lang aime>data s, t;
<syntaxhighlight lang="aime">data s, t;
# Copy -t- into -s-
# Copy -t- into -s-
b_copy(s, t);
b_copy(s, t);
Line 283: Line 320:
# or:
# or:
s = t;
s = t;
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
In ALGOL 68 strings are simply flexible length arrays of CHAR;
In ALGOL 68 strings are simply flexible length arrays of CHAR;


<lang algol68>(
<syntaxhighlight lang="algol68">(
STRING src:="Hello", dest;
STRING src:="Hello", dest;
dest:=src
dest:=src
)</lang>
)</syntaxhighlight>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% strings are (fixed length) values in algol W. Assignment makes a copy %
% strings are (fixed length) values in algol W. Assignment makes a copy %
string(10) a, copyOfA;
string(10) a, copyOfA;
Line 302: Line 339:
a := "new value";
a := "new value";
write( a, copyOfA )
write( a, copyOfA )
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 310: Line 347:
=={{header|Apex}}==
=={{header|Apex}}==
In Apex, Strings are a primitive data type
In Apex, Strings are a primitive data type
<lang apex>String original = 'Test';
<syntaxhighlight lang="apex">String original = 'Test';
String cloned = original;
String cloned = original;
//"original == cloned" is true
//"original == cloned" is true


cloned += ' more';
cloned += ' more';
//"original == cloned" is false</lang>
//"original == cloned" is false</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>set src to "Hello"
<syntaxhighlight lang="applescript">set src to "Hello"
set dst to src</lang>
set dst to src</syntaxhighlight>


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




</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>a: new "Hello"
<syntaxhighlight lang="rebol">a: new "Hello"
b: a ; reference the same string
b: a ; reference the same string


Line 424: Line 461:
'd ++ "World"
'd ++ "World"
print d
print d
print c</lang>
print c</syntaxhighlight>


{{out}}
{{out}}
Line 434: Line 471:


=={{header|Asymptote}}==
=={{header|Asymptote}}==
<lang Asymptote>string src, dst;
<syntaxhighlight lang="asymptote">string src, dst;
src = "Hello";
src = "Hello";
dst = src;
dst = src;
src = " world...";
src = " world...";
write(dst, src);</lang>
write(dst, src);</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


<lang autohotkey>src := "Hello"
<syntaxhighlight lang="autohotkey">src := "Hello"
dst := src</lang>
dst := src</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==


<lang autoit>$Src= "Hello"
<syntaxhighlight lang="autoit">$Src= "Hello"
$dest = $Src</lang>
$dest = $Src</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
a = "a string"
a = "a string"
b = a
b = a
sub(/a/, "X", a) # modify a
sub(/a/, "X", a) # modify a
print b # b is a copy, not a reference to...
print b # b is a copy, not a reference to...
}</lang>
}</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
<lang axe>Lbl STRCPY
<syntaxhighlight lang="axe">Lbl STRCPY
r₁→S
r₁→S
While {r₂}
While {r₂}
Line 469: Line 506:
0→{r₁}
0→{r₁}
S
S
Return</lang>
Return</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
Line 475: Line 512:
To copy a string in Babel is the same as copying any other object. Use the cp operator to make a deep-copy.
To copy a string in Babel is the same as copying any other object. Use the cp operator to make a deep-copy.


<lang babel>babel> "Hello, world\n" dup cp dup 0 "Y" 0 1 move8
<syntaxhighlight lang="babel">babel> "Hello, world\n" dup cp dup 0 "Y" 0 1 move8
babel> << <<
babel> << <<
Yello, world
Yello, world
Hello, world
Hello, world
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 488: Line 525:


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>100 DEF FN P(A) = PEEK (A) + PEEK(A + 1) * 256 : FOR I = FN P(105) TO FN P(107) - 1 STEP 7 : ON PEEK(I + 1) < 128 OR PEEK(I) > 127 GOTO 130 : ON LEFT$(P$, 1) <> CHR$(PEEK(I)) GOTO 130
<syntaxhighlight lang="applesoftbasic">100 DEF FN P(A) = PEEK (A) + PEEK(A + 1) * 256 : FOR I = FN P(105) TO FN P(107) - 1 STEP 7 : ON PEEK(I + 1) < 128 OR PEEK(I) > 127 GOTO 130 : ON LEFT$(P$, 1) <> CHR$(PEEK(I)) GOTO 130
110 IF LEN(P$) > 1 THEN ON PEEK(I + 1) = 128 GOTO 130 : IF MID$(P$, 2, 1) <> CHR$(PEEK(I + 1) - 128) GOTO 130
110 IF LEN(P$) > 1 THEN ON PEEK(I + 1) = 128 GOTO 130 : IF MID$(P$, 2, 1) <> CHR$(PEEK(I + 1) - 128) GOTO 130
120 POKE I + 4, P / 256 : POKE I + 3, P - PEEK(I + 4) * 256 : RETURN
120 POKE I + 4, P / 256 : POKE I + 3, P - PEEK(I + 4) * 256 : RETURN
130 NEXT I : STOP</lang>
130 NEXT I : STOP</syntaxhighlight>


<lang ApplesoftBasic>S$ = "HELLO" : REM S$ IS THE ORIGINAL STRING
<syntaxhighlight lang="applesoftbasic">S$ = "HELLO" : REM S$ IS THE ORIGINAL STRING
C$ = S$ : REM C$ IS THE COPY</lang>
C$ = S$ : REM C$ IS THE COPY</syntaxhighlight>


<lang ApplesoftBasic>P$ = "S" : P = 53637 : GOSUB 100"POINT STRING S AT SOMETHING ELSE
<syntaxhighlight lang="applesoftbasic">P$ = "S" : P = 53637 : GOSUB 100"POINT STRING S AT SOMETHING ELSE
?S$
?S$
?C$</lang>
?C$</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
Line 509: Line 546:
When using string variables by value:
When using string variables by value:


<lang freebasic>a$ = "I am here"
<syntaxhighlight lang="freebasic">a$ = "I am here"
b$ = a$
b$ = a$
a$ = "Hello world..."
a$ = "Hello world..."
PRINT a$, b$</lang>
PRINT a$, b$</syntaxhighlight>


This will print "Hello world...I am here". The variables point to their individual memory areas so they contain different strings. Now consider the following code:
This will print "Hello world...I am here". The variables point to their individual memory areas so they contain different strings. Now consider the following code:


<lang freebasic>a$ = "Hello world..."
<syntaxhighlight lang="freebasic">a$ = "Hello world..."
LOCAL b TYPE STRING
LOCAL b TYPE STRING
b = a$
b = a$
a$ = "Goodbye..."
a$ = "Goodbye..."
PRINT a$, b</lang>
PRINT a$, b</syntaxhighlight>


This will print "Goodbye...Goodbye..." because the variable 'b' points to the same memory area as 'a$'.
This will print "Goodbye...Goodbye..." because the variable 'b' points to the same memory area as 'a$'.


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang freebasic>src$ = "Hello"
<syntaxhighlight lang="freebasic">src$ = "Hello"
dst$ = src$
dst$ = src$
src$ = " world..."
src$ = " world..."
print dst$; src$</lang>
print dst$; src$</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
Line 534: Line 571:
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{works with|PB|7.1}}
{{works with|PB|7.1}}
<lang qbasic>src$ = "Hello" ' is the original string
<syntaxhighlight lang="qbasic">src$ = "Hello" ' is the original string
dst$ = src$ ' is the copy
dst$ = src$ ' is the copy
src$ = " world..."
src$ = " world..."
PRINT dst$; src$</lang>
PRINT dst$; src$</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
Line 543: Line 580:
{{works with|BASIC256}}
{{works with|BASIC256}}
{{works with|Yabasic}}
{{works with|Yabasic}}
<lang qbasic>LET src$ = "Hello"
<syntaxhighlight lang="qbasic">LET src$ = "Hello"
LET dst$ = src$
LET dst$ = src$
LET src$ = " world..."
LET src$ = " world..."
PRINT dst$; src$
PRINT dst$; src$
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>src$ = "Hello"
<syntaxhighlight lang="yabasic">src$ = "Hello"
dst$ = src$
dst$ = src$
src$ = " world..."
src$ = " world..."
print dst$, src$
print dst$, src$
end</lang>
end</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang basic>10 A$ = "HELLO"
<syntaxhighlight lang="basic">10 A$ = "HELLO"
20 REM COPY CONTENTS OF A$ TO B$
20 REM COPY CONTENTS OF A$ TO B$
30 B$ = A$
30 B$ = A$
Line 563: Line 600:
50 A$ = "HI"
50 A$ = "HI"
60 REM DISPLAY CONTENTS
60 REM DISPLAY CONTENTS
70 PRINT A$, B$</lang>
70 PRINT A$, B$</syntaxhighlight>
Commodore BASIC can't do pointers or 'reference to'
Commodore BASIC can't do pointers or 'reference to'


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Creating a new reference to an existing string is not possible, or at least not easy. (You could probably do it with <code>PEEK</code>s and <code>POKE</code>s.) This program demonstrates that an assignment statement copies a string, by showing that the two strings can afterwards be independently modified.
Creating a new reference to an existing string is not possible, or at least not easy. (You could probably do it with <code>PEEK</code>s and <code>POKE</code>s.) This program demonstrates that an assignment statement copies a string, by showing that the two strings can afterwards be independently modified.
<lang basic>10 LET A$="BECAUSE I DO NOT HOPE TO TURN AGAIN"
<syntaxhighlight lang="basic">10 LET A$="BECAUSE I DO NOT HOPE TO TURN AGAIN"
20 LET B$=A$
20 LET B$=A$
30 LET A$=A$( TO 21)
30 LET A$=A$( TO 21)
Line 574: Line 611:
50 PRINT A$
50 PRINT A$
60 LET B$=A$+B$(22 TO 29)
60 LET B$=A$+B$(22 TO 29)
70 PRINT B$</lang>
70 PRINT B$</syntaxhighlight>
{{out}}
{{out}}
<pre>BECAUSE I DO NOT HOPE TO TURN AGAIN
<pre>BECAUSE I DO NOT HOPE TO TURN AGAIN
Line 583: Line 620:
Since the only variables are environment variables,
Since the only variables are environment variables,
creating a string copy is fairly straightforward:
creating a string copy is fairly straightforward:
<lang dos>set src=Hello
<syntaxhighlight lang="dos">set src=Hello
set dst=%src%</lang>
set dst=%src%</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> source$ = "Hello, world!"
<syntaxhighlight lang="bbcbasic"> source$ = "Hello, world!"
REM Copy the contents of a string:
REM Copy the contents of a string:
Line 598: Line 635:
?(^same$+4) = ?(^source$+4)
?(^same$+4) = ?(^source$+4)
?(^same$+5) = ?(^source$+5)
?(^same$+5) = ?(^source$+5)
PRINT same$</lang>
PRINT same$</syntaxhighlight>

=={{header|Binary Lambda Calculus}}==

In BLC, every value is immutable, including byte-strings. So one never needs to copy them; references are shared.


=={{header|BQN}}==
=={{header|BQN}}==
Line 604: Line 645:


String copying in BQN is left to be defined by the implementation, but [[CBQN]] and [[mlochbaum/BQN]](main implementations) copy only the reference until the original source is modified.
String copying in BQN is left to be defined by the implementation, but [[CBQN]] and [[mlochbaum/BQN]](main implementations) copy only the reference until the original source is modified.
<lang bqn>a ← "Hello"
<syntaxhighlight lang="bqn">a ← "Hello"
b ← a
b ← a
•Show a‿b
•Show a‿b
a ↩ "hi"
a ↩ "hi"
•Show a‿b</lang><lang bqn>⟨ "Hello" "Hello" ⟩
•Show a‿b</syntaxhighlight><syntaxhighlight lang="bqn">⟨ "Hello" "Hello" ⟩
⟨ "hi" "Hello" ⟩</lang>
⟨ "hi" "Hello" ⟩</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Line 618: Line 659:
Still, you won't be able to test whether you got the original or a copy other than by looking at overall memory usage of the Bracmat program at the OS-level or by closely timing comparison operations.
Still, you won't be able to test whether you got the original or a copy other than by looking at overall memory usage of the Bracmat program at the OS-level or by closely timing comparison operations.
You obtain a new reference to a string or a copy of the string by simple assignment using the <code>=</code> or the <code>:</code> operator:
You obtain a new reference to a string or a copy of the string by simple assignment using the <code>=</code> or the <code>:</code> operator:
<lang bracmat>abcdef:?a;
<syntaxhighlight lang="bracmat">abcdef:?a;
!a:?b;
!a:?b;


Line 626: Line 667:
!a:!b { variables a and b are the same and probably referencing the same string }
!a:!b { variables a and b are the same and probably referencing the same string }
!a:!d { variables a and d are also the same but not referencing the same string }
!a:!d { variables a and d are also the same but not referencing the same string }
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h> /* exit(), free() */
<syntaxhighlight lang="c">#include <stdlib.h> /* exit(), free() */
#include <stdio.h> /* fputs(), perror(), printf() */
#include <stdio.h> /* fputs(), perror(), printf() */
#include <string.h>
#include <string.h>
Line 688: Line 729:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


==={{libheader|BSD libc}}===
==={{libheader|BSD libc}}===
<lang c>#include <stdlib.h> /* exit() */
<syntaxhighlight lang="c">#include <stdlib.h> /* exit() */
#include <stdio.h> /* fputs(), printf() */
#include <stdio.h> /* fputs(), printf() */
#include <string.h>
#include <string.h>
Line 712: Line 753:


return 0;
return 0;
}</lang>
}</syntaxhighlight>

==={{libheader|Gadget}}===

Versión 2, using Gadget library.

Link:

https://github.com/DanielStuardo/Gadget


<syntaxhighlight lang="c">

#include <gadget/gadget.h>

LIB_GADGET_START

Main
String v, w = "this message is a message";
Let( v, "Hello world!");
Print "v = %s\nw = %s\n\n", v,w;
Get_fn_let( v, Upper(w) );
Print "v = %s\nw = %s\n\n", v,w;

Stack{
Store ( v, Str_tran_last( Upper(w), "MESSAGE", "PROOF" ) );
}Stack_off;
Print "v = %s\nw = %s\n\n", v,w;
Free secure v, w;

End
</syntaxhighlight>
{{out}}
<pre>
v = Hello world!
w = this message is a message

v = THIS MESSAGE IS A MESSAGE
w = this message is a message

v = THIS MESSAGE IS A PROOF
w = this message is a message
</pre>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>string src = "Hello";
<syntaxhighlight lang="csharp">string src = "Hello";
string dst = src;</lang>
string dst = src;</syntaxhighlight>


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


Line 728: Line 816:
original = "Now we change the original! ";
original = "Now we change the original! ";
std::cout << "my_copy still is " << my_copy << std::endl;
std::cout << "my_copy still is " << my_copy << std::endl;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang clojure>(let [s "hello"
<syntaxhighlight lang="clojure">(let [s "hello"
s1 s]
s1 s]
(println s s1))</lang>
(println s s1))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{trans|C#}}
{{trans|C#}}
<lang cobol>MOVE "Hello" TO src
<syntaxhighlight lang="cobolfree">MOVE "Hello" TO src
MOVE src TO dst</lang>
MOVE src TO dst</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
Line 746: Line 834:
Hence, any string copy operations are by value.
Hence, any string copy operations are by value.


<lang coldfusion><cfset stringOrig = "I am a string." />
<syntaxhighlight lang="coldfusion"><cfset stringOrig = "I am a string." />
<cfset stringCopy = stringOrig /></lang>
<cfset stringCopy = stringOrig /></syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(let* ((s1 "Hello") ; s1 is a variable containing a string
<syntaxhighlight lang="lisp">(let* ((s1 "Hello") ; s1 is a variable containing a string
(s1-ref s1) ; another variable with the same value
(s1-ref s1) ; another variable with the same value
(s2 (copy-seq s1))) ; s2 has a distinct string object with the same contents
(s2 (copy-seq s1))) ; s2 has a distinct string object with the same contents
Line 760: Line 848:
(fill s2 #\!) ; overwrite s2
(fill s2 #\!) ; overwrite s2
(princ s1)
(princ s1)
(princ s2)) ; will print "Hello!!!!!"</lang>
(princ s2)) ; will print "Hello!!!!!"</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
<lang oberon2>
<syntaxhighlight lang="oberon2">
VAR
VAR
str1: ARRAY 128 OF CHAR;
str1: ARRAY 128 OF CHAR;
str2: ARRAY 32 OF CHAR;
str2: ARRAY 32 OF CHAR;
str3: ARRAY 25 OF CHAR;
str3: ARRAY 25 OF CHAR;
</syntaxhighlight>
</lang>
...
...
<lang oberon2>
<syntaxhighlight lang="oberon2">
str1 := "abcdefghijklmnopqrstuvwxyz";
str1 := "abcdefghijklmnopqrstuvwxyz";
str3 := str1; (* don't compile, incompatible assignement *)
str3 := str1; (* don't compile, incompatible assignement *)
str3 := str1$; (* runtime error, string too long *)
str3 := str1$; (* runtime error, string too long *)
str2 := str1$; (* OK *)
str2 := str1$; (* OK *)
</syntaxhighlight>
</lang>


=={{header|Computer/zero Assembly}}==
=={{header|Computer/zero Assembly}}==
Assuming a string to be a zero-terminated array of bytes, this program takes a string beginning at address <tt>src</tt> and makes a copy of it beginning at address <tt>dest</tt>. As an example, we copy the string "Rosetta".
Assuming a string to be a zero-terminated array of bytes, this program takes a string beginning at address <tt>src</tt> and makes a copy of it beginning at address <tt>dest</tt>. As an example, we copy the string "Rosetta".
<lang czasm>ldsrc: LDA src
<syntaxhighlight lang="czasm">ldsrc: LDA src
stdest: STA dest
stdest: STA dest
BRZ done ; 0-terminated
BRZ done ; 0-terminated
Line 806: Line 894:
0
0


dest:</lang>
dest:</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang crystal>s1 = "Hello"
<syntaxhighlight lang="crystal">s1 = "Hello"
s2 = s1</lang>
s2 = s1</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==


<lang d>void main() {
<syntaxhighlight lang="d">void main() {
string src = "This is a string";
string src = "This is a string";


Line 825: Line 913:
// copy just the fat reference of the string
// copy just the fat reference of the string
auto dest3 = src;
auto dest3 = src;
}</lang>
}</syntaxhighlight>


=={{header|dc}}==
=={{header|dc}}==
<lang dc>[a string] # push "a string" on the main stack
<syntaxhighlight lang="dc">[a string] # push "a string" on the main stack
d # duplicate the top value
d # duplicate the top value
f # show the current contents of the main stack</lang>
f # show the current contents of the main stack</syntaxhighlight>


{{Out}}
{{Out}}
Line 840: Line 928:
Delphi strings are reference counted with [[wp:Copy-on-write|copy on write]] semantics.
Delphi strings are reference counted with [[wp:Copy-on-write|copy on write]] semantics.


<lang Delphi>program CopyString;
<syntaxhighlight lang="delphi">program CopyString;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 854: Line 942:
Writeln(s1);
Writeln(s1);
Writeln(s2);
Writeln(s2);
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 873: Line 961:
Strings in Dyalect are immutable:
Strings in Dyalect are immutable:


<lang dyalect>var src = "foobar"
<syntaxhighlight lang="dyalect">var src = "foobar"
var dst = src</lang>
var dst = src</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
Line 882: Line 970:
However, one can still create a copy of a string
However, one can still create a copy of a string
by concatenating it with an empty string.
by concatenating it with an empty string.
<lang dejavu>local :orgininal "this is the original"
<syntaxhighlight lang="dejavu">local :orgininal "this is the original"
local :scopy concat( original "" )
local :scopy concat( original "" )
!. scopy</lang>
!. scopy</syntaxhighlight>
{{out}}
{{out}}
<pre>"this is the original"</pre>
<pre>"this is the original"</pre>
Line 896: Line 984:
=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>a$ = "hello"
<syntaxhighlight lang="text">
b$ = a$</lang>
a$ = "hello"
b$ = a$
print b$
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
Strings are immutable. A copy will return the same object.
Strings are immutable. A copy will return the same object.
<lang scheme>
<syntaxhighlight lang="scheme">
(define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing
(define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing
→ #syntax:string-copy
→ #syntax:string-copy
Line 908: Line 999:
t → "abc"
t → "abc"
(eq? s t) → #t ;; same reference, same object
(eq? s t) → #t ;; same reference, same object
</syntaxhighlight>
</lang>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
Expects the final character of a string to be marked with a 1 in the least significant bit, as in [[Hello world/Line printer#EDSAC order code]]. The source string should be loaded at <i>θ</i>+34; it is copied into storage tank 6. The copy is then printed out.
Expects the final character of a string to be marked with a 1 in the least significant bit, as in [[Hello world/Line printer#EDSAC order code]]. The source string should be loaded at <i>θ</i>+34; it is copied into storage tank 6. The copy is then printed out.
<lang edsac>[ Copy a string
<syntaxhighlight lang="edsac">[ Copy a string
=============
=============


Line 974: Line 1,065:
ED
ED


EZPF</lang>
EZPF</syntaxhighlight>
{{out}}
{{out}}
<pre>ROSETTA CODE</pre>
<pre>ROSETTA CODE</pre>


=={{header|Elena}}==
=={{header|Elena}}==
<lang elena>
<syntaxhighlight lang="elena">
var src := "Hello";
var src := "Hello";
var dst := src; // copying the reference
var dst := src; // copying the reference
var copy := src.clone(); // copying the content
var copy := src.clone(); // copying the content
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>src = "Hello"
<syntaxhighlight lang="elixir">src = "Hello"
dst = src</lang>
dst = src</syntaxhighlight>


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


<lang Lisp>(let* ((str1 "hi")
<syntaxhighlight lang="lisp">(let* ((str1 "hi")
(str1-ref str1)
(str1-ref str1)
(str2 (copy-sequence str1)))
(str2 (copy-sequence str1)))
Line 997: Line 1,088:
(eq str1 str2) ;=> nil
(eq str1 str2) ;=> nil
(equal str1 str1-ref) ;=> t
(equal str1 str1-ref) ;=> t
(equal str1 str2)) ;=> t</lang>
(equal str1 str2)) ;=> t</syntaxhighlight>

=={{header|EMal}}==
in EMal strings are mutable
<syntaxhighlight lang="emal">
text original = "Yellow world"
text ref = original # copying the reference
text copied = *original # copying the content
original[0] = "H" # texts are indexable and mutable
original[5] = ","
ref.append("!") # texts are coercible and growable
copied += "?"
^|
| original == ref == "Hello, world!"
| copied == "Yellow world?"
|^
</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>Src = "Hello".
<syntaxhighlight lang="erlang">Src = "Hello".
Dst = Src.</lang>
Dst = Src.</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
Line 1,015: Line 1,122:
Euphoria will complain at the time your code does the assignment.
Euphoria will complain at the time your code does the assignment.


<lang Euphoria>sequence first = "ABC"
<syntaxhighlight lang="euphoria">sequence first = "ABC"
sequence newOne = first</lang>
sequence newOne = first</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
.NET strings are immutable, so it is usually not useful to make a deep copy.
.NET strings are immutable, so it is usually not useful to make a deep copy.
However if needed, it is possible using a static method of the <code>System.String</code> type:
However if needed, it is possible using a static method of the <code>System.String</code> type:
<lang fsharp>let str = "hello"
<syntaxhighlight lang="fsharp">let str = "hello"
let additionalReference = str
let additionalReference = str
let deepCopy = System.String.Copy( str )
let deepCopy = System.String.Copy( str )


printfn "%b" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true
printfn "%b" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true
printfn "%b" <| System.Object.ReferenceEquals( str, deepCopy ) // prints false</lang>
printfn "%b" <| System.Object.ReferenceEquals( str, deepCopy ) // prints false</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Line 1,033: Line 1,140:
Strings will be immutable in a future release.
Strings will be immutable in a future release.


<lang factor>"This is a mutable string." dup ! reference
<syntaxhighlight lang="factor">"This is a mutable string." dup ! reference
"Let's make a deal!" dup clone ! copy
"Let's make a deal!" dup clone ! copy
"New" " string" append . ! new string
"New" " string" append . ! new string
"New string"</lang>
"New string"</syntaxhighlight>


Factor string buffers (sbufs) are mutable and growable.
Factor string buffers (sbufs) are mutable and growable.


<lang factor>SBUF" Grow me!" dup " OK." append
<syntaxhighlight lang="factor">SBUF" Grow me!" dup " OK." append
SBUF" Grow me! OK."</lang>
SBUF" Grow me! OK."</syntaxhighlight>


Convert a string buffer to a string.
Convert a string buffer to a string.


<lang factor>SBUF" I'll be a string someday." >string .
<syntaxhighlight lang="factor">SBUF" I'll be a string someday." >string .
"I'll be a string someday."</lang>
"I'll be a string someday."</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Line 1,055: Line 1,162:
Thus the way you copy a string depends on where the source string comes from:
Thus the way you copy a string depends on where the source string comes from:


<lang forth>\ Allocate two string buffers
<syntaxhighlight lang="forth">\ Allocate two string buffers
create stringa 256 allot
create stringa 256 allot
create stringb 256 allot
create stringb 256 allot
Line 1,063: Line 1,170:


\ Copy the contents of one string buffer into another
\ Copy the contents of one string buffer into another
stringa count stringb place</lang>
stringa count stringb place</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==


<lang fortran>str2 = str1</lang>
<syntaxhighlight lang="fortran">str2 = str1</syntaxhighlight>


Because Fortran uses fixed length character strings if str1 is shorter than str2 then str2 is padded out with trailing spaces.
Because Fortran uses fixed length character strings if str1 is shorter than str2 then str2 is padded out with trailing spaces.
Line 1,073: Line 1,180:


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


Dim s As String = "This is a string"
Dim s As String = "This is a string"
Line 1,084: Line 1,191:
Print
Print
Print *u, StrPtr(*u)
Print *u, StrPtr(*u)
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,096: Line 1,203:
=={{header|Frink}}==
=={{header|Frink}}==
Strings are immutable after construction, so "copying" a string just creates a new reference to a string. All string manipulation routines return a new string.
Strings are immutable after construction, so "copying" a string just creates a new reference to a string. All string manipulation routines return a new string.
<lang frink>
<syntaxhighlight lang="frink">
a = "Monkey"
a = "Monkey"
b = a
b = a
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang>
<syntaxhighlight lang="text">
include "ConsoleWindow"
include "NSLog.incl"


CFStringRef original, copy
dim as Str15 s, c

s = "Hello!"
original = @"Hello!"
c = s
copy = fn StringWithString( original )
print c

</lang>
NSLog( @"%@", copy )

HandleEvents
</syntaxhighlight>


Output:
Output:
<pre>
<pre>
"Hello!"
Hello!
</pre>
</pre>


Line 1,121: Line 1,232:


'''[https://gambas-playground.proko.eu/?gist=b88224f45b9b5be09eafdf069b059076 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=b88224f45b9b5be09eafdf069b059076 Click this link to run this code]'''
<lang gambas>Public Sub main()
<syntaxhighlight lang="gambas">Public Sub main()
Dim src As String
Dim src As String
Dim dst As String
Dim dst As String
Line 1,130: Line 1,241:
Print src
Print src
Print dst
Print dst
End</lang>
End</syntaxhighlight>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>#In GAP strings are lists of characters. An affectation simply copy references
<syntaxhighlight lang="gap">#In GAP strings are lists of characters. An affectation simply copy references
a := "more";
a := "more";
b := a;
b := a;
Line 1,145: Line 1,256:
b{[1..4]} := "less";
b{[1..4]} := "less";
a;
a;
# "more"</lang>
# "more"</syntaxhighlight>


=={{header|GML}}==
=={{header|GML}}==
<lang GML>src = "string";
<syntaxhighlight lang="gml">src = "string";
dest = src;</lang>
dest = src;</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Just use assignment:
Just use assignment:
<lang go>src := "Hello"
<syntaxhighlight lang="go">src := "Hello"
dst := src</lang>
dst := src</syntaxhighlight>
Strings in Go are immutable. Because of this, there is no need to distinguish between copying the contents and making an additional reference.
Strings in Go are immutable. Because of this, there is no need to distinguish between copying the contents and making an additional reference.
Technically, Go strings are immutable byte slices.
Technically, Go strings are immutable byte slices.
Line 1,162: Line 1,273:
but the language does not specify this behavior or make any guarantees about it.
but the language does not specify this behavior or make any guarantees about it.


::<lang go>package main
::<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,183: Line 1,294:
// creature string
// creature string
fmt.Println("creature =", creature) // creature = jellyfish
fmt.Println("creature =", creature) // creature = jellyfish
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Line 1,190: Line 1,301:


Example and counter-example:
Example and counter-example:
<lang groovy>def string = 'Scooby-doo-bee-doo' // assigns string object to a variable reference
<syntaxhighlight lang="groovy">def string = 'Scooby-doo-bee-doo' // assigns string object to a variable reference
def stringRef = string // assigns another variable reference to the same object
def stringRef = string // assigns another variable reference to the same object
def stringCopy = new String(string) // copies string value into a new object, and assigns to a third variable reference</lang>
def stringCopy = new String(string) // copies string value into a new object, and assigns to a third variable reference</syntaxhighlight>


Test Program:
Test Program:
<lang groovy>assert string == stringRef // they have equal values (like Java equals(), not like Java ==)
<syntaxhighlight lang="groovy">assert string == stringRef // they have equal values (like Java equals(), not like Java ==)
assert string.is(stringRef) // they are references to the same objext (like Java ==)
assert string.is(stringRef) // they are references to the same objext (like Java ==)
assert string == stringCopy // they have equal values
assert string == stringCopy // they have equal values
assert ! string.is(stringCopy) // they are references to different objects (like Java !=)</lang>
assert ! string.is(stringCopy) // they are references to different objects (like Java !=)</syntaxhighlight>


'''Caveat Lector''': Strings are immutable objects in Groovy, so it is wasteful and utterly unnecessary to ever make copies of them within a Groovy program.
'''Caveat Lector''': Strings are immutable objects in Groovy, so it is wasteful and utterly unnecessary to ever make copies of them within a Groovy program.
Line 1,204: Line 1,315:
=={{header|GUISS}}==
=={{header|GUISS}}==


<lang guiss>Start.Programs,Accessories,Notepad,
<syntaxhighlight lang="guiss">Start.Programs,Accessories,Notepad,
Type:Hello world[pling],Highlight:Hello world[pling],
Type:Hello world[pling],Highlight:Hello world[pling],
Menu,Edit,Copy,Menu,Edit,Paste</lang>
Menu,Edit,Copy,Menu,Edit,Paste</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>cSource := "Hello World"
<syntaxhighlight lang="visualfoxpro">cSource := "Hello World"
cDestination := cSource</lang>
cDestination := cSource</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 1,218: Line 1,329:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>src = "Hello World"
<syntaxhighlight lang="hicest">src = "Hello World"
dst = src</lang>
dst = src</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>//Strings are immutable in 'i'.
<syntaxhighlight lang="i">//Strings are immutable in 'i'.
software {
software {
a = "Hello World"
a = "Hello World"
Line 1,232: Line 1,343:
print(b)
print(b)
}
}
</syntaxhighlight>
</lang>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Strings in Icon are immutable.
Strings in Icon are immutable.
<lang icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
a := "qwerty"
a := "qwerty"
b := a
b := a
b[2+:4] := "uarterl"
b[2+:4] := "uarterl"
write(a," -> ",b)
write(a," -> ",b)
end</lang>
end</syntaxhighlight>


Under the covers 'b' is created as a reference to the same string as 'a';
Under the covers 'b' is created as a reference to the same string as 'a';
Line 1,253: Line 1,364:


=={{header|J}}==
=={{header|J}}==
<lang j>src =: 'hello'
<syntaxhighlight lang="j">src =: 'hello'
dest =: src</lang>
dest =: src</syntaxhighlight>


J has copy-on-write semantics.
J has copy-on-write semantics.
Line 1,261: Line 1,372:
=={{header|Java}}==
=={{header|Java}}==
In Java, Strings are immutable, so it doesn't make that much difference to copy it.
In Java, Strings are immutable, so it doesn't make that much difference to copy it.
<lang java>String src = "Hello";
<syntaxhighlight lang="java">String src = "Hello";
String newAlias = src;
String newAlias = src;
String strCopy = new String(src);
String strCopy = new String(src);
Line 1,267: Line 1,378:
//"newAlias == src" is true
//"newAlias == src" is true
//"strCopy == src" is false
//"strCopy == src" is false
//"strCopy.equals(src)" is true</lang>
//"strCopy.equals(src)" is true</syntaxhighlight>


Instead, maybe you want to create a <code>StringBuffer</code> (mutable string) from an existing String or StringBuffer:
Instead, maybe you want to create a <code>StringBuffer</code> (mutable string) from an existing String or StringBuffer:
<lang java>StringBuffer srcCopy = new StringBuffer("Hello");</lang>
<syntaxhighlight lang="java">StringBuffer srcCopy = new StringBuffer("Hello");</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Objects can be copied in JavaScript via simple reassignment.
Objects can be copied in JavaScript via simple reassignment.
Changes to the properties of one will be reflected in the other:
Changes to the properties of one will be reflected in the other:
<lang javascript>var container = {myString: "Hello"};
<syntaxhighlight lang="javascript">var container = {myString: "Hello"};
var containerCopy = container; // Now both identifiers refer to the same object
var containerCopy = container; // Now both identifiers refer to the same object


containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"</lang>
containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"</syntaxhighlight>


If you copy property values with reassignment, such as properties of the global object (<code>window</code> in browsers), only the value will be copied and not the reference
If you copy property values with reassignment, such as properties of the global object (<code>window</code> in browsers), only the value will be copied and not the reference
<lang javascript>var a = "Hello";
<syntaxhighlight lang="javascript">var a = "Hello";
var b = a; // Same as saying window.b = window.a
var b = a; // Same as saying window.b = window.a


b = "Goodbye" // b contains a copy of a's value and a will still return "Hello"</lang>
b = "Goodbye" // b contains a copy of a's value and a will still return "Hello"</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
<lang joy>"hello" dup</lang>
<syntaxhighlight lang="joy">"hello" dup</syntaxhighlight>


Strings are immutable.
Strings are immutable.
Line 1,294: Line 1,405:
jq is a functional language and all data types, including strings, are immutable. If a string were to be copied (e.g. by exploding and imploding it), the resultant string would be equal in all respects to the original, and from the jq programmer's perspective, the two would be identical.
jq is a functional language and all data types, including strings, are immutable. If a string were to be copied (e.g. by exploding and imploding it), the resultant string would be equal in all respects to the original, and from the jq programmer's perspective, the two would be identical.


jq does however have a type of variable, though their values actually don't change -- they are just context-dependent. For example, consider the sequence of steps in the following function:<lang jq>def demo:
jq does however have a type of variable, though their values actually don't change -- they are just context-dependent. For example, consider the sequence of steps in the following function:<syntaxhighlight lang="jq">def demo:
"abc" as $s # assignment of a string to a variable
"abc" as $s # assignment of a string to a variable
| $s as $t # $t points to the same string as $s
| $s as $t # $t points to the same string as $s
Line 1,302: Line 1,413:


demo
demo
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
"abc"
"abc"
Line 1,308: Line 1,419:
=={{header|Julia}}==
=={{header|Julia}}==
Strings are immutable in Julia. Assignment of one string valued variable to another is effectively a copy, as subsequent changes to either variable have no effect on the other.
Strings are immutable in Julia. Assignment of one string valued variable to another is effectively a copy, as subsequent changes to either variable have no effect on the other.
<syntaxhighlight lang="julia">
<lang Julia>
s = "Rosetta Code"
s = "Rosetta Code"
t = s
t = s
Line 1,317: Line 1,428:


println("s = \"", s, "\" and, after this change, t = \"", t, "\"")
println("s = \"", s, "\" and, after this change, t = \"", t, "\"")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,326: Line 1,437:


=={{header|KonsolScript}}==
=={{header|KonsolScript}}==
<lang KonsolScript>Var:String str1 = "Hello";
<syntaxhighlight lang="konsolscript">Var:String str1 = "Hello";
Var:String str2 = str1;</lang>
Var:String str2 = str1;</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>val s = "Hello"
<syntaxhighlight lang="scala">val s = "Hello"
val alias = s // alias === s
val alias = s // alias === s
val copy = "" + s // copy !== s</lang>
val copy = "" + s // copy !== s</syntaxhighlight>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
In LabVIEW, one can simply wire an input to more than one output.<br/>
In LabVIEW, one can simply wire an input to more than one output.<br/>
{{VI snippet}}<br/>[[File:LabVIEW_Copy_a_string.png]]
{{VI snippet}}<br/>[[File:LabVIEW_Copy_a_string.png]]

=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def S1 hello world} // set S1 to "hello world"
-> S1
{S1} // get the value of S1
-> hello world

{def S2 S1} // define S2 as S1
-> S2
{S2} // the value of S2 is S1
-> S1
{{S2}} // get the value of the value of S2
-> hello world

{def S3 {S1}} // set S3 to the value of S1
-> S3
{S3} // get the value of S3
-> hello world
</syntaxhighlight>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>'hello dup</lang>
<syntaxhighlight lang="lang5">'hello dup</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
While other datatypes like arrays require ->asCopy & ->asCopyDeep methods,
While other datatypes like arrays require ->asCopy & ->asCopyDeep methods,
assigning strings creates a copy, not a reference, as is seen below.
assigning strings creates a copy, not a reference, as is seen below.
<lang Lasso>local(x = 'I saw a rhino!')
<syntaxhighlight lang="lasso">local(x = 'I saw a rhino!')
local(y = #x)
local(y = #x)


Line 1,361: Line 1,492:
#x //I saw one too
#x //I saw one too
'\r'
'\r'
#y //it was grey.</lang>
#y //it was grey.</syntaxhighlight>


=={{header|Latitude}}==
=={{header|Latitude}}==
Strings are immutable in Latitude, so it is seldom necessary to explicitly copy one. However, a copy can be distinguished from the original using <code>===</code>
Strings are immutable in Latitude, so it is seldom necessary to explicitly copy one. However, a copy can be distinguished from the original using <code>===</code>
<lang latitude>a := "Hello".
<syntaxhighlight lang="latitude">a := "Hello".
b := a.
b := a.
c := a clone.
c := a clone.
Line 1,371: Line 1,502:
println: a == c. ; True
println: a == c. ; True
println: a === b. ; True
println: a === b. ; True
println: a === c. ; False</lang>
println: a === c. ; False</syntaxhighlight>


=={{header|LC3 Assembly}}==
=={{header|LC3 Assembly}}==
Copying a string is the same as copying any other zero-terminated array. This program copies the string at <tt>SRC</tt> to <tt>COPY</tt>, then prints the copy to show it has worked.
Copying a string is the same as copying any other zero-terminated array. This program copies the string at <tt>SRC</tt> to <tt>COPY</tt>, then prints the copy to show it has worked.
<lang lc3asm> .ORIG 0x3000
<syntaxhighlight lang="lc3asm"> .ORIG 0x3000


LEA R1,SRC
LEA R1,SRC
Line 1,396: Line 1,527:
COPY .BLKW 128
COPY .BLKW 128


.END</lang>
.END</syntaxhighlight>
{{out}}
{{out}}
<pre>What, has this thing appeared again tonight?</pre>
<pre>What, has this thing appeared again tonight?</pre>
Line 1,402: Line 1,533:
=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>(let* ((a '"data assigned to a")
<syntaxhighlight lang="lisp">(let* ((a '"data assigned to a")
(b a))
(b a))
(: io format '"Contents of 'b': ~s~n" (list b)))</lang>
(: io format '"Contents of 'b': ~s~n" (list b)))</syntaxhighlight>


{{out}}
{{out}}
Line 1,413: Line 1,544:
One can also use <code>set</code> to copy a sting when one is in the LFE REPL:
One can also use <code>set</code> to copy a sting when one is in the LFE REPL:


<lang lisp>> (set a '"data")
<syntaxhighlight lang="lisp">> (set a '"data")
"data"
"data"
> a
> a
Line 1,420: Line 1,551:
"data"
"data"
> b
> b
"data"</lang>
"data"</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>src$ = "Hello"
<syntaxhighlight lang="lb">src$ = "Hello"
dest$ = src$
dest$ = src$
print src$
print src$
print dest$
print dest$
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>str = "Hello world!"
<syntaxhighlight lang="lingo">str = "Hello world!"
str2 = str</lang>
str2 = str</syntaxhighlight>


Syntax-wise strings are not immuatable in Lingo. You can alter an existing string without new assignment:
Syntax-wise strings are not immuatable in Lingo. You can alter an existing string without new assignment:


<lang lingo>put "X" before str
<syntaxhighlight lang="lingo">put "X" before str
put "X" after str
put "X" after str
put "X" into char 6 of str
put "X" into char 6 of str
put str
put str
-- "XHellX world!X"</lang>
-- "XHellX world!X"</syntaxhighlight>


But memory-wise they are immutable: Lingo internally stores references to strings, and as soon as a string is altered, a new copy is created on the fly, so other references to the original string are not affected by the change.
But memory-wise they are immutable: Lingo internally stores references to strings, and as soon as a string is altered, a new copy is created on the fly, so other references to the original string are not affected by the change.


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>+ scon : STRING_CONSTANT;
<syntaxhighlight lang="lisaac">+ scon : STRING_CONSTANT;
+ svar : STRING;
+ svar : STRING;


Line 1,452: Line 1,583:
svar.append "!\n";
svar.append "!\n";


svar.print;</lang>
svar.print;</syntaxhighlight>
STRING_CONSTANT is immutable, STRING is not.
STRING_CONSTANT is immutable, STRING is not.


=={{header|Little}}==
=={{header|Little}}==
<lang C>string a = "A string";
<syntaxhighlight lang="c">string a = "A string";
string b = a;
string b = a;
a =~ s/$/\./;
a =~ s/$/\./;
puts(a);
puts(a);
puts(b);</lang>
puts(b);</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>put "foo" into bar
<syntaxhighlight lang="livecode">put "foo" into bar
put bar into baz
put bar into baz
answer bar && baz</lang>
answer bar && baz</syntaxhighlight>


Copies are nearly always made, on function calls parameters may be passed by reference (pointer) by prepending @ to a parameter in the function definition, however this is the only case where it is usually performed.
Copies are nearly always made, on function calls parameters may be passed by reference (pointer) by prepending @ to a parameter in the function definition, however this is the only case where it is usually performed.
Line 1,471: Line 1,602:
=={{header|Logo}}==
=={{header|Logo}}==
As a functional language, words are normally treated as symbols and cannot be modified. The EQUAL? predicate compares contents instead of identity. In [[UCB Logo]] the .EQ predicate tests for "thing" identity.
As a functional language, words are normally treated as symbols and cannot be modified. The EQUAL? predicate compares contents instead of identity. In [[UCB Logo]] the .EQ predicate tests for "thing" identity.
<lang logo>make "a "foo
<syntaxhighlight lang="logo">make "a "foo
make "b "foo
make "b "foo
print .eq :a :b ; true, identical symbols are reused
print .eq :a :b ; true, identical symbols are reused
Line 1,480: Line 1,611:
make "c word :b "|| ; force a copy of the contents of a word by appending the empty word
make "c word :b "|| ; force a copy of the contents of a word by appending the empty word
print equal? :b :c ; true
print equal? :b :c ; true
print .eq :b :c ; false</lang>
print .eq :b :c ; false</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Lua strings are immutable, so only one reference to each string exists.
Lua strings are immutable, so only one reference to each string exists.
<lang lua>
<syntaxhighlight lang="lua">
a = "string"
a = "string"
b = a
b = a
print(a == b) -->true
print(a == b) -->true
print(b) -->string</lang>
print(b) -->string</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
In Maple, you cannot really copy a string in the sense that there can be two copies of the string in memory. As soon as you create a second copy of a string that already exists, it get turned into a reference to the first copy. However, you can copy a reference to a string by a simple assignment statement.
In Maple, you cannot really copy a string in the sense that there can be two copies of the string in memory. As soon as you create a second copy of a string that already exists, it get turned into a reference to the first copy. However, you can copy a reference to a string by a simple assignment statement.
<syntaxhighlight lang="maple">
<lang Maple>
> s := "some string";
> s := "some string";
s := "some string"
s := "some string"
Line 1,506: Line 1,637:


> u := t: # copy reference
> u := t: # copy reference
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>a="Hello World"
<syntaxhighlight lang="mathematica">a="Hello World"
b=a</lang>
b=a</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>string1 = 'Hello';
<syntaxhighlight lang="matlab">string1 = 'Hello';
string2 = string1;</lang>
string2 = string1;</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* It's possible in Maxima to access individual characters by subscripts, but it's not the usual way.
<syntaxhighlight lang="maxima">/* It's possible in Maxima to access individual characters by subscripts, but it's not the usual way.
Also, the result is "Lisp character", which cannot be used by other Maxima functions except cunlisp. The usual
Also, the result is "Lisp character", which cannot be used by other Maxima functions except cunlisp. The usual
way to access characters is charat, returning a "Maxima character" (actually a one characte string). With the latter,
way to access characters is charat, returning a "Maxima character" (actually a one characte string). With the latter,
Line 1,535: Line 1,666:


c;
c;
"losers"</lang>
"losers"</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>str1 = "Hello"
<syntaxhighlight lang="maxscript">str1 = "Hello"
str2 = copy str1</lang>
str2 = copy str1</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Line 1,545: Line 1,676:
Metafont will always copy a string (does not make references).
Metafont will always copy a string (does not make references).


<lang metafont>string s, a;
<syntaxhighlight lang="metafont">string s, a;
s := "hello";
s := "hello";
a := s;
a := s;
Line 1,551: Line 1,682:
message s; % writes "hello world"
message s; % writes "hello world"
message a; % writes "hello"
message a; % writes "hello"
end</lang>
end</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>phrase = "hi"
<syntaxhighlight lang="miniscript">phrase = "hi"
copy = phrase
copy = phrase
print phrase
print phrase
print copy</lang>
print copy</syntaxhighlight>


=={{header|MIPS Assembly}}==
=={{header|MIPS Assembly}}==
This does a full copy of the string, not just copying the pointer to the string's contents.
This does a full copy of the string, not just copying the pointer to the string's contents.
<lang mips>.data
<syntaxhighlight lang="mips">.data
.text
.text
Line 1,583: Line 1,714:
addi $sp, $sp, 4
addi $sp, $sp, 4
jr $ra
jr $ra
</syntaxhighlight>
</lang>


=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>src = "Hello"
<syntaxhighlight lang="mirah">src = "Hello"
new_alias = src
new_alias = src


Line 1,594: Line 1,725:
puts 'non-interned strings are not equal' if str_copy != src
puts 'non-interned strings are not equal' if str_copy != src
puts 'compare strings with equals()' if str_copy.equals(src)
puts 'compare strings with equals()' if str_copy.equals(src)
</syntaxhighlight>
</lang>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Strings in Modula-3 have the type <code>TEXT</code>.
Strings in Modula-3 have the type <code>TEXT</code>.
<lang modula3>VAR src: TEXT := "Foo";
<syntaxhighlight lang="modula3">VAR src: TEXT := "Foo";
VAR dst: TEXT := src;</lang>
VAR dst: TEXT := src;</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang>SET S1="Greetings, Planet"
<syntaxhighlight lang="text">SET S1="Greetings, Planet"
SET S2=S1</lang>
SET S2=S1</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang nanoquery>a = "Hello"
<syntaxhighlight lang="nanoquery">a = "Hello"
b = a</lang>
b = a</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<lang Neko>var src = "Hello"
<syntaxhighlight lang="neko">var src = "Hello"
var dst = src</lang>
var dst = src</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
Nemerle gives you the option of declaring a variable - even a string - as mutable, so the caveats of languages with only immutable strings don't necessarily apply. However, Nemerle binds the value of the string to the new name when copying; to sort of emulate copying a reference you can use lazy evaluation.
Nemerle gives you the option of declaring a variable - even a string - as mutable, so the caveats of languages with only immutable strings don't necessarily apply. However, Nemerle binds the value of the string to the new name when copying; to sort of emulate copying a reference you can use lazy evaluation.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using Nemerle;
using Nemerle;
Line 1,632: Line 1,763:
// I am not changed
// I am not changed
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
In addition to the string capabilities provided by the Java String libraries (see [[#Java|Java]] for some examples) NetRexx provides comprehensive string capabilities through the built-in Rexx type. Rexx strings can be copied by simple assignment; as follows:
In addition to the string capabilities provided by the Java String libraries (see [[#Java|Java]] for some examples) NetRexx provides comprehensive string capabilities through the built-in Rexx type. Rexx strings can be copied by simple assignment; as follows:
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,645: Line 1,776:


say s1
say s1
say s2</lang>
say s2</syntaxhighlight>
In this example a string is created, the string is copied then the copy is modified with the <tt>changestr</tt> built-in function. Finally both strings are displayed to confirm that the original string wasn't modified by the call to <tt>changestr</tt>.
In this example a string is created, the string is copied then the copy is modified with the <tt>changestr</tt> built-in function. Finally both strings are displayed to confirm that the original string wasn't modified by the call to <tt>changestr</tt>.


Line 1,655: Line 1,786:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(define (assert f msg) (if (not f) (println msg)))
<syntaxhighlight lang="newlisp">(define (assert f msg) (if (not f) (println msg)))


(setq s "Greetings!" c (copy s))
(setq s "Greetings!" c (copy s))
Line 1,674: Line 1,805:
true
true


</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>var
<syntaxhighlight lang="nim">var
c = "This is a string"
c = "This is a string"
d = c # Copy c into a new string</lang>
d = c # Copy c into a new string</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 A$ = "HELLO"
<syntaxhighlight lang="ns-hubasic">10 A$ = "HELLO"
20 B$ = A$
20 B$ = A$
30 A$ = "HI"
30 A$ = "HI"
40 PRINT A$, B$</lang>
40 PRINT A$, B$</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>MODULE CopyString;
<syntaxhighlight lang="oberon2">MODULE CopyString;
TYPE
TYPE
String = ARRAY 128 OF CHAR;
String = ARRAY 128 OF CHAR;
Line 1,697: Line 1,828:
a := "plain string";
a := "plain string";
COPY(a,b);
COPY(a,b);
END CopyString.</lang>
END CopyString.</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>a := "GoodBye!";
<syntaxhighlight lang="objeck">a := "GoodBye!";
b := a;</lang>
b := a;</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 1,708: Line 1,839:
Note that both <code>copy</code> and <code>initWithString:</code>/<code>stringWithString:</code> are optimized to return the original string object (possibly retained) if it is immutable.
Note that both <code>copy</code> and <code>initWithString:</code>/<code>stringWithString:</code> are optimized to return the original string object (possibly retained) if it is immutable.


<lang objc>NSString *original = @"Literal String";
<syntaxhighlight lang="objc">NSString *original = @"Literal String";
NSString *new = [original copy];
NSString *new = [original copy];
NSString *anotherNew = [NSString stringWithString:original];
NSString *anotherNew = [NSString stringWithString:original];
NSString *newMutable = [original mutableCopy];</lang>
NSString *newMutable = [original mutableCopy];</syntaxhighlight>


Mutable strings - you can get either new mutable (if you use <code>mutableCopy</code>) or immutable (if you use <code>copy</code>) string:
Mutable strings - you can get either new mutable (if you use <code>mutableCopy</code>) or immutable (if you use <code>copy</code>) string:


<lang objc>NSMutableString *original = [NSMutableString stringWithString:@"Literal String"];
<syntaxhighlight lang="objc">NSMutableString *original = [NSMutableString stringWithString:@"Literal String"];
NSString *immutable = [original copy];
NSString *immutable = [original copy];
NSString *anotherImmutable = [NSString stringWithString:original];
NSString *anotherImmutable = [NSString stringWithString:original];
NSMutableString *mutable = [original mutableCopy];</lang>
NSMutableString *mutable = [original mutableCopy];</syntaxhighlight>


Copying a CString into an NSString:
Copying a CString into an NSString:


<lang objc>const char *cstring = "I'm a plain C string";
<syntaxhighlight lang="objc">const char *cstring = "I'm a plain C string";
NSString *string = [NSString stringWithUTF8String:cstring];</lang>
NSString *string = [NSString stringWithUTF8String:cstring];</syntaxhighlight>


Copying from data, possibly not null terminated:
Copying from data, possibly not null terminated:


<lang objc>char bytes[] = "some data";
<syntaxhighlight lang="objc">char bytes[] = "some data";
NSString *string = [[NSString alloc] initWithBytes:bytes length:9 encoding:NSASCIIStringEncoding];</lang>
NSString *string = [[NSString alloc] initWithBytes:bytes length:9 encoding:NSASCIIStringEncoding];</syntaxhighlight>


And of course, if a C string is needed, you can use standard functions like strcpy.
And of course, if a C string is needed, you can use standard functions like strcpy.


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let src = "foobar"</lang>
<syntaxhighlight lang="ocaml">let src = "foobar"</syntaxhighlight>
<br/>
<br/>
Before OCaml 4.02 (2014), strings were mutable and explicit deep copying was needed:
Before OCaml 4.02 (2014), strings were mutable and explicit deep copying was needed:
<lang ocaml>let dst = String.copy src</lang>
<syntaxhighlight lang="ocaml">let dst = String.copy src</syntaxhighlight>
<br/>
<br/>
Between 4.02 and 4.06 (2017), immutable strings were optionally enabled via a flag: <code>-safe-string</code>. A <code>Bytes</code> module was added to provide safe and unsafe mutable views on strings. The two modules were synonymous unless the aforementioned flag was added.
Between 4.02 and 4.06 (2017), immutable strings were optionally enabled via a flag: <code>-safe-string</code>. A <code>Bytes</code> module was added to provide safe and unsafe mutable views on strings. The two modules were synonymous unless the aforementioned flag was added.
<lang ocaml>(* Transition-period synonymy between types, explicit type annotations are just for emphasis *)
<syntaxhighlight lang="ocaml">(* Transition-period synonymy between types, explicit type annotations are just for emphasis *)
let dst1 : string = Bytes.copy (src : bytes)
let dst1 : string = Bytes.copy (src : bytes)
let dst2 : bytes = Bytes.copy (src : string)
let dst2 : bytes = Bytes.copy (src : string)
(* fails to compile with -safe-string *)</lang>
(* fails to compile with -safe-string *)</syntaxhighlight>
<br/>
<br/>
After 4.06, immutable strings became the default, <code>Bytes</code> still exists, but its type is now distinct. The only way to get mutable strings and type synonymy back is at configure-time on the compiler itself.<br/>
After 4.06, immutable strings became the default, <code>Bytes</code> still exists, but its type is now distinct. The only way to get mutable strings and type synonymy back is at configure-time on the compiler itself.<br/>
<code>String.copy</code> issues a deprecation warning, and a (shallow) copy would simply be an assignment by default:
<code>String.copy</code> issues a deprecation warning, and a (shallow) copy would simply be an assignment by default:
<lang ocaml>let dst = src</lang>
<syntaxhighlight lang="ocaml">let dst = src</syntaxhighlight>
To get a mutable deep-copy still, just convert the string to bytes via <code>Bytes.of_string</code>, which copies for safety, or <code>String.sub/map/init/..</code> for an immutable copy.
To get a mutable deep-copy still, just convert the string to bytes via <code>Bytes.of_string</code>, which copies for safety, or <code>String.sub/map/init/..</code> for an immutable copy.
<br/>
<br/>
Line 1,753: Line 1,884:


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>str2 = str1</lang>
<syntaxhighlight lang="octave">str2 = str1</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
To make a copy of the reference, just dup the string
To make a copy of the reference, just dup the string
<lang Oforth>"abcde" dup</lang>
<syntaxhighlight lang="oforth">"abcde" dup</syntaxhighlight>


There is no need to copy a string content as strings are immutable. If really needed :
There is no need to copy a string content as strings are immutable. If really needed :
<lang Oforth>StringBuffer new "abcde" << </lang>
<syntaxhighlight lang="oforth">StringBuffer new "abcde" << </syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define a "The String.")
(define a "The String.")


Line 1,779: Line 1,910:
(print "c is an a: " (eq? a c))
(print "c is an a: " (eq? a c))
(print "c same as a: " (equal? a c))
(print "c same as a: " (equal? a c))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,793: Line 1,924:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>/* Rexx ***************************************************************
<syntaxhighlight lang="oorexx">/* Rexx ***************************************************************
* 16.05.2013 Walter Pachl
* 16.05.2013 Walter Pachl
**********************************************************************/
**********************************************************************/
Line 1,810: Line 1,941:
Say 's2='s2
Say 's2='s2
i1=s1~identityhash; Say 's1~identityhash='i1
i1=s1~identityhash; Say 's1~identityhash='i1
i2=s2~identityhash; Say 's2~identityhash='i2</lang>
i2=s2~identityhash; Say 's2~identityhash='i2</syntaxhighlight>
{{out}}
{{out}}
<pre>s1=This is a Rexx string
<pre>s1=This is a Rexx string
Line 1,822: Line 1,953:


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
string s, t="hello"
string s, t="hello"
s=t
s=t
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Assignment in GP always copies.
Assignment in GP always copies.
<lang parigp>s1=s</lang>
<syntaxhighlight lang="parigp">s1=s</syntaxhighlight>


In PARI, strings can be copied and references can be made.
In PARI, strings can be copied and references can be made.
<lang C>GEN string_copy = gcopy(string);
<syntaxhighlight lang="c">GEN string_copy = gcopy(string);
GEN string_ref = string;</lang>
GEN string_ref = string;</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
''See also: [[#Delphi|Delphi]]''

<lang pascal>program in,out;
<syntaxhighlight lang="pascal" highlight="9,13,15">program copyAString;
var

{ The Extended Pascal `string` schema data type
type
is essentially a `packed array[1..capacity] of char`. }
source, destination: string(80);
pString = ^string;
begin

source := 'Hello world!';
var
{ In Pascal _whole_ array data type values can be copied by assignment. }

destination := source;
s1,s2 : string ;
{ Provided `source` is a _non-empty_ string value
pStr : pString ;
you can copy in Extended Pascal sub-ranges _of_ _string_ types, too.

Note, the sub-range notation is not permitted for a `bindable` data type. }
begin
destination := source[1..length(source)];

{ You can also employ Extended Pascal’s `writeStr` routine: }
/* direct copy */
writeStr(destination, source);
s1 := 'Now is the time for all good men to come to the aid of their party.'
end.</syntaxhighlight>
s2 := s1 ;

writeln(s1);
writeln(s2);

/* By Reference */
pStr := @s1 ;
writeln(pStr^);

pStr := @s2 ;
writeln(pStr^);

end;</lang>


=={{header|Perl}}==
=={{header|Perl}}==
Line 1,870: Line 1,989:
To copy a string, just use ordinary assignment:
To copy a string, just use ordinary assignment:


<lang perl>my $original = 'Hello.';
<syntaxhighlight lang="perl">my $original = 'Hello.';
my $new = $original;
my $new = $original;
$new = 'Goodbye.';
$new = 'Goodbye.';
print "$original\n"; # prints "Hello."</lang>
print "$original\n"; # prints "Hello."</syntaxhighlight>


To create a reference to an existing string, so that modifying the referent changes the original string, use a backslash:
To create a reference to an existing string, so that modifying the referent changes the original string, use a backslash:


<lang perl>my $original = 'Hello.';
<syntaxhighlight lang="perl">my $original = 'Hello.';
my $ref = \$original;
my $ref = \$original;
$$ref = 'Goodbye.';
$$ref = 'Goodbye.';
print "$original\n"; # prints "Goodbye."</lang>
print "$original\n"; # prints "Goodbye."</syntaxhighlight>


If you want a new name for the same string, so that you can modify it without dereferencing a reference, assign a reference to a typeglob:
If you want a new name for the same string, so that you can modify it without dereferencing a reference, assign a reference to a typeglob:


<lang perl>my $original = 'Hello.';
<syntaxhighlight lang="perl">my $original = 'Hello.';
our $alias;
our $alias;
local *alias = \$original;
local *alias = \$original;
$alias = 'Good evening.';
$alias = 'Good evening.';
print "$original\n"; # prints "Good evening."</lang>
print "$original\n"; # prints "Good evening."</syntaxhighlight>


Note that <tt>our $alias</tt>, though in most cases a no-op, is necessary under stricture. Beware that <tt>local</tt> binds dynamically, so any subroutines called in this scope will see (and possibly modify!) the value of <tt>$alias</tt> assigned here.
Note that <tt>our $alias</tt>, though in most cases a no-op, is necessary under stricture. Beware that <tt>local</tt> binds dynamically, so any subroutines called in this scope will see (and possibly modify!) the value of <tt>$alias</tt> assigned here.


To make a lexical variable that is an alias of some other variable, the [http://search.cpan.org/perldoc?Lexical::Alias Lexical::Alias] module can be used:
To make a lexical variable that is an alias of some other variable, the [http://search.cpan.org/perldoc?Lexical::Alias Lexical::Alias] module can be used:
<lang perl>use Lexical::Alias;
<syntaxhighlight lang="perl">use Lexical::Alias;
my $original = 'Hello.';
my $original = 'Hello.';
my $alias;
my $alias;
alias $alias, $original;
alias $alias, $original;
$alias = 'Good evening.';
$alias = 'Good evening.';
print "$original\n"; # prints "Good evening."</lang>
print "$original\n"; # prints "Good evening."</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
Use of strings is utterly intuitive with no unexpected side effects. For example
Use of strings is utterly intuitive with no unexpected side effects. For example
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">string</span> <span style="color: #000000;">one</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"feed"</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">one</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"feed"</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">two</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">one</span> <span style="color: #000080;font-style:italic;">-- (two becomes "feed", one remains "feed")</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">two</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">one</span> <span style="color: #000080;font-style:italic;">-- (two becomes "feed", one remains "feed")</span>
Line 1,909: Line 2,028:
<span style="color: #000000;">one<span style="color: #0000FF;">[<span style="color: #000000;">1<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'n'</span> <span style="color: #000080;font-style:italic;">-- (two remains "food", one becomes "need")</span>
<span style="color: #000000;">one<span style="color: #0000FF;">[<span style="color: #000000;">1<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'n'</span> <span style="color: #000080;font-style:italic;">-- (two remains "food", one becomes "need")</span>
<span style="color: #0000FF;">?<span style="color: #0000FF;">{<span style="color: #000000;">one<span style="color: #0000FF;">,<span style="color: #000000;">two<span style="color: #0000FF;">}
<span style="color: #0000FF;">?<span style="color: #0000FF;">{<span style="color: #000000;">one<span style="color: #0000FF;">,<span style="color: #000000;">two<span style="color: #0000FF;">}
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,918: Line 2,037:
=={{header|PHP}}==
=={{header|PHP}}==


<lang php>$src = "Hello";
<syntaxhighlight lang="php">$src = "Hello";
$dst = $src;</lang>
$dst = $src;</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Use <code>copy_term/1</code> to ensure that the original string is not changed.
Use <code>copy_term/1</code> to ensure that the original string is not changed.
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
S1 = "string",
S1 = "string",
println(s1=S1),
println(s1=S1),
Line 1,938: Line 2,057:
println(s4=S4),
println(s4=S4),


nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 1,950: Line 2,069:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(setq Str1 "abcdef")
<syntaxhighlight lang="picolisp">(setq Str1 "abcdef")
(setq Str2 Str1) # Create a reference to that symbol
(setq Str2 Str1) # Create a reference to that symbol
(setq Str3 (name Str1)) # Create new symbol with name "abcdef"</lang>
(setq Str3 (name Str1)) # Create new symbol with name "abcdef"</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
string hi = "Hello World.";
string hi = "Hello World.";
string ih = hi;
string ih = hi;
}</lang>
}</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli> declare (s1, s2) character (20) varying;
<syntaxhighlight lang="pli"> declare (s1, s2) character (20) varying;
s1 = 'now is the time';
s1 = 'now is the time';
s2 = s1;</lang>
s2 = s1;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 1,969: Line 2,088:
In Pop11 normal data are represented by references, so plain assignment will copy references. To copy data one has to use copy procedure:
In Pop11 normal data are represented by references, so plain assignment will copy references. To copy data one has to use copy procedure:


<lang pop11>vars src, dst;
<syntaxhighlight lang="pop11">vars src, dst;
'Hello' -> src;
'Hello' -> src;
copy(src) -> dst;</lang>
copy(src) -> dst;</syntaxhighlight>


One can also combine assignment (initialization) with variable declarations:
One can also combine assignment (initialization) with variable declarations:


<lang pop11>vars src='Hello';
<syntaxhighlight lang="pop11">vars src='Hello';
vars dst=copy(src);</lang>
vars dst=copy(src);</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
In PostScript,
In PostScript,
<lang postscript>(hello) dup length string copy</lang>
<syntaxhighlight lang="postscript">(hello) dup length string copy</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Since PowerShell uses .NET behind the scenes and .NET strings are immutable you can simply assign the same string to another variable without breaking anything:
Since PowerShell uses .NET behind the scenes and .NET strings are immutable you can simply assign the same string to another variable without breaking anything:
<lang powershell>$str = "foo"
<syntaxhighlight lang="powershell">$str = "foo"
$dup = $str</lang>
$dup = $str</syntaxhighlight>
To actually create a copy the <code>Clone()</code> method can be used:
To actually create a copy the <code>Clone()</code> method can be used:
<lang powershell>$dup = $str.Clone()</lang>
<syntaxhighlight lang="powershell">$dup = $str.Clone()</syntaxhighlight>


=={{header|ProDOS}}==
=={{header|ProDOS}}==
<lang ProDOS>editvar /newvar /value=a /userinput=1 /title=Enter a string to be copied:
<syntaxhighlight lang="prodos">editvar /newvar /value=a /userinput=1 /title=Enter a string to be copied:
editvar /newvar /value=b /userinput=1 /title=Enter current directory of the string:
editvar /newvar /value=b /userinput=1 /title=Enter current directory of the string:
editvar /newvar /value=c /userinput=1 /title=Enter file to copy to:
editvar /newvar /value=c /userinput=1 /title=Enter file to copy to:
copy -a- from -b- to -c- </lang>
copy -a- from -b- to -c- </syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Values in Prolog are immutable so unifying with a variable that already has the value of a string will effectively copy that string.
Values in Prolog are immutable so unifying with a variable that already has the value of a string will effectively copy that string.
You cannot reassign a value once it has been unified, it is not logical to have a value equal more than one thing.
You cannot reassign a value once it has been unified, it is not logical to have a value equal more than one thing.
<lang prolog>?- A = "A test string", A = B.
<syntaxhighlight lang="prolog">?- A = "A test string", A = B.
A = B, B = "A test string".</lang>
A = B, B = "A test string".</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>src$ = "Hello"
<syntaxhighlight lang="purebasic">src$ = "Hello"
dst$ = src$</lang>
dst$ = src$</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 2,009: Line 2,128:
Since strings are immutable, all copy operations return the same string, with the reference count increased as appropriate
Since strings are immutable, all copy operations return the same string, with the reference count increased as appropriate


<lang python>>>> src = "hello"
<syntaxhighlight lang="python">>>> src = "hello"
>>> a = src
>>> a = src
>>> b = src[:]
>>> b = src[:]
Line 2,016: Line 2,135:
>>> d = copy.deepcopy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
>>> src is a is b is c is d
True</lang>
True</syntaxhighlight>


To actually copy a string:
To actually copy a string:


<lang python>>>> a = 'hello'
<syntaxhighlight lang="python">>>> a = 'hello'
>>> b = ''.join(a)
>>> b = ''.join(a)
>>> a == b
>>> a == b
True
True
>>> b is a ### Might be True ... depends on "interning" implementation details!
>>> b is a ### Might be True ... depends on "interning" implementation details!
False</lang>
False</syntaxhighlight>


As a result of object "interning" some strings such as the empty string and single character strings like 'a' may be references to the same object regardless of copying. This can potentially happen with any Python immutable object and should be of no consequence to any proper code.
As a result of object "interning" some strings such as the empty string and single character strings like 'a' may be references to the same object regardless of copying. This can potentially happen with any Python immutable object and should be of no consequence to any proper code.
Line 2,036: Line 2,155:
<br>
<br>
Strings are immutable.
Strings are immutable.
<lang Quackery>$ "hello" dup</lang>
<syntaxhighlight lang="quackery">$ "hello" dup</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Copy a string by value:
Copy a string by value:
<lang R>str1 <- "abc"
<syntaxhighlight lang="r">str1 <- "abc"
str2 <- str1</lang>
str2 <- str1</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 2,059: Line 2,178:
(string-fill! s3 #\!)
(string-fill! s3 #\!)
(printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!"
(printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!"
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,065: Line 2,184:


There is no special handling needed to copy a string; just assign it to a new variable:
There is no special handling needed to copy a string; just assign it to a new variable:
<lang perl6>my $original = 'Hello.';
<syntaxhighlight lang="raku" line>my $original = 'Hello.';
my $copy = $original;
my $copy = $original;
say $copy; # prints "Hello."
say $copy; # prints "Hello."
$copy = 'Goodbye.';
$copy = 'Goodbye.';
say $copy; # prints "Goodbye."
say $copy; # prints "Goodbye."
say $original; # prints "Hello."</lang>
say $original; # prints "Hello."</syntaxhighlight>


You can also bind a new variable to an existing one so that each refers to, and can modify the same string.
You can also bind a new variable to an existing one so that each refers to, and can modify the same string.
<lang perl6>my $original = 'Hello.';
<syntaxhighlight lang="raku" line>my $original = 'Hello.';
my $bound := $original;
my $bound := $original;
say $bound; # prints "Hello."
say $bound; # prints "Hello."
$bound = 'Goodbye.';
$bound = 'Goodbye.';
say $bound; # prints "Goodbye."
say $bound; # prints "Goodbye."
say $original; # prints "Goodbye."</lang>
say $original; # prints "Goodbye."</syntaxhighlight>


<!-- SqrtNegInf 2016-01-16 This is NYI, so until such time as it is, leaving this section commented
<!-- SqrtNegInf 2016-01-16 This is NYI, so until such time as it is, leaving this section commented
You can also create a read-only binding which will allow read access to the string but prevent modification except through the original variable.
You can also create a read-only binding which will allow read access to the string but prevent modification except through the original variable.
<lang perl6># y $original = 'Hello.';
<syntaxhighlight lang="raku" line># y $original = 'Hello.';
#my $bound-ro ::= $original;
#my $bound-ro ::= $original;
#say $bound-ro; # prints "Hello."
#say $bound-ro; # prints "Hello."
Line 2,093: Line 2,212:
say $bound-ro; # prints "Hello."
say $bound-ro; # prints "Hello."
$original = 'Goodbye.';
$original = 'Goodbye.';
say $bound-ro; # prints "Goodbye."</lang>
say $bound-ro; # prints "Goodbye."</syntaxhighlight>
-->
-->


Line 2,100: Line 2,219:
Copy a string by reference:
Copy a string by reference:


<lang raven>'abc' as a
<syntaxhighlight lang="raven">'abc' as a
a as b</lang>
a as b</syntaxhighlight>


Copy a string by value:
Copy a string by value:


<lang raven>'abc' as a
<syntaxhighlight lang="raven">'abc' as a
a copy as b</lang>
a copy as b</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "String Copy"
Title: "String Copy"
URL: http://rosettacode.org/wiki/Copy_a_string
URL: http://rosettacode.org/wiki/Copy_a_string
Line 2,129: Line 2,248:


y: copy/part skip x 2 3
y: copy/part skip x 2 3
print ["Partial copy from offset:" mold x "," mold y]</lang>
print ["Partial copy from offset:" mold x "," mold y]</syntaxhighlight>


{{out}}
{{out}}
Line 2,140: Line 2,259:


=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
Red[]
Red[]
originalString: "hello wordl"
originalString: "hello wordl"
Line 2,146: Line 2,265:
; OR
; OR
copiedString2: copy originalString
copiedString2: copy originalString
</syntaxhighlight>
</lang>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>'this_is_a_string dup s:temp</lang>
<syntaxhighlight lang="retro">'this_is_a_string dup s:temp</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,160: Line 2,279:
Also note that &nbsp; ''all'' &nbsp; REXX values (variables) are
Also note that &nbsp; ''all'' &nbsp; REXX values (variables) are
stored as (varying length) &nbsp; ''character strings''.
stored as (varying length) &nbsp; ''character strings''.
<lang rexx>src = "this is a string"
<syntaxhighlight lang="rexx">src = "this is a string"
dst = src</lang>
dst = src</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
cStr1 = "Hello!" # create original string
cStr1 = "Hello!" # create original string
cStr2 = cStr1 # make new string from original
cStr2 = cStr1 # make new string from original
</syntaxhighlight>
</lang>


=={{header|RLaB}}==
=={{header|RLaB}}==
<lang RLaB>>> s1 = "A string"
<syntaxhighlight lang="rlab">>> s1 = "A string"
A string
A string
>> s2 = s1
>> s2 = s1
A string</lang>
A string</syntaxhighlight>


=={{header|Robotic}}==
=={{header|Robotic}}==
<lang robotic>
<syntaxhighlight lang="robotic">
set "$string1" to "This is a string"
set "$string1" to "This is a string"
set "$string2" to "$string1"
set "$string2" to "$string1"
* "&$string2&"
* "&$string2&"
</syntaxhighlight>
</lang>


=={{header|RPL}}==
Copy a string in stack:
DUP
Copy a string from one variable to another:
"Example" 'STR1' STO
STR1 'STR2' STO
=={{header|Ruby}}==
=={{header|Ruby}}==
In Ruby, String are mutable.
In Ruby, String are mutable.
<lang ruby>original = "hello"
<syntaxhighlight lang="ruby">original = "hello"
reference = original # copies reference
reference = original # copies reference
copy1 = original.dup # instance of original.class
copy1 = original.dup # instance of original.class
Line 2,192: Line 2,317:
p reference #=> "hello world!"
p reference #=> "hello world!"
p copy1 #=> "hello"
p copy1 #=> "hello"
p copy2 #=> "hello"</lang>
p copy2 #=> "hello"</syntaxhighlight>


There is a method of Object#clone, too, in the copy of the object.
There is a method of Object#clone, too, in the copy of the object.
<lang ruby>original = "hello".freeze # prevents further modifications
<syntaxhighlight lang="ruby">original = "hello".freeze # prevents further modifications
copy1 = original.dup # copies contents (without status)
copy1 = original.dup # copies contents (without status)
copy2 = original.clone # copies contents (with status)
copy2 = original.clone # copies contents (with status)
Line 2,201: Line 2,326:
p copy1 << " world!" #=> "hello world!"
p copy1 << " world!" #=> "hello world!"
p copy2.frozen? #=> true
p copy2.frozen? #=> true
p copy2 << " world!" #=> can't modify frozen String (RuntimeError)</lang>
p copy2 << " world!" #=> can't modify frozen String (RuntimeError)</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>origString$ = "Hello!" ' create original string
<syntaxhighlight lang="runbasic">origString$ = "Hello!" ' create original string
newString$ = origString$ ' make new strig from original</lang>
newString$ = origString$ ' make new strig from original</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
let s1 = "A String";
let s1 = "A String";
let mut s2 = s1;
let mut s2 = s1;
Line 2,215: Line 2,340:


println!("s1 = {}, s2 = {}", s1, s2);
println!("s1 = {}, s2 = {}", s1, s2);
}</lang>
}</syntaxhighlight>


Output: <lang>s1 = A String, s2 = Another String</lang>
Output: <syntaxhighlight lang="text">s1 = A String, s2 = Another String</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
main is
main is
s ::= "a string";
s ::= "a string";
Line 2,226: Line 2,351:
-- s1 is a copy
-- s1 is a copy
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala> val src = "Hello"
<syntaxhighlight lang="scala"> val src = "Hello"
// Its actually not a copy but a reference
// Its actually not a copy but a reference
// That is not a problem because String is immutable
// That is not a problem because String is immutable
Line 2,241: Line 2,366:
assert((src eq cop)) // Still no copyed image
assert((src eq cop)) // Still no copyed image
val copy = src.reverse.reverse // Finally double reverse makes a copy
val copy = src.reverse.reverse // Finally double reverse makes a copy
assert(src == copy && !(src eq copy))// Prove, but it really makes no sense.</lang>
assert(src == copy && !(src eq copy))// Prove, but it really makes no sense.</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define dst (string-copy src))</lang>
<syntaxhighlight lang="scheme">(define dst (string-copy src))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|sed}}==
In ''sed'', there are two distinct locations for storing a string: The "pattern space" and the "hold space". The <code>h</code> command copies pattern space to hold space. The <code>g</code> command copies hold space to pattern space.


=={{header|Seed7}}==
<lang seed7>var string: dest is "";
<syntaxhighlight lang="seed7">var string: dest is "";


dest := "Hello";</lang>
dest := "Hello";</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>(* In SenseTalk, assignments normally always make copies of values. *)
<syntaxhighlight lang="sensetalk">(* In SenseTalk, assignments normally always make copies of values. *)


put "glorious" into myWord
put "glorious" into myWord
Line 2,270: Line 2,397:
put "myRef: " & myRef
put "myRef: " & myRef
put "another: " & another
put "another: " & another
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,280: Line 2,407:


=={{header|Shiny}}==
=={{header|Shiny}}==
<lang shiny>src: 'hello'
<syntaxhighlight lang="shiny">src: 'hello'
cpy: src</lang>
cpy: src</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var original = "hello"; # new String object
<syntaxhighlight lang="ruby">var original = "hello"; # new String object
var reference = original; # points at the original object
var reference = original; # points at the original object
var copy1 = String.new(original); # creates a new String object
var copy1 = String.new(original); # creates a new String object
var copy2 = original+''; # ==//==</lang>
var copy2 = original+''; # ==//==</syntaxhighlight>
=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN
TEXT ORIGINAL, REFERENCE, COPY1;
TEXT ORIGINAL, REFERENCE, COPY1;


Line 2,317: Line 2,444:
OUTTEXT(COPY1);
OUTTEXT(COPY1);
OUTIMAGE;
OUTIMAGE;
END;</lang>
END;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,328: Line 2,455:
=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>[ | :s | s == s copy] applyTo: {'hello'}. "returns False"</lang>
<syntaxhighlight lang="slate">[ | :s | s == s copy] applyTo: {'hello'}. "returns False"</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


<lang smalltalk>|s1 s2|
<syntaxhighlight lang="smalltalk">|s1 s2|
"bind the var s1 to the object string on the right"
"bind the var s1 to the object string on the right"
s1 := 'i am a string'.
s1 := 'i am a string'.
Line 2,338: Line 2,465:
s2 := s1.
s2 := s1.
"bind s2 to a copy of the object bound to s1"
"bind s2 to a copy of the object bound to s1"
s2 := (s1 copy).</lang>
s2 := (s1 copy).</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4>
<syntaxhighlight lang="snobol4">
* copy a to b
* copy a to b
b = a = "test"
b = a = "test"
Line 2,349: Line 2,476:
b "t" = "T"
b "t" = "T"
output = b
output = b
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,362: Line 2,489:


Instead, maybe you want to create a <code>CharArray.array</code> (mutable string) from an existing <code>string</code>:
Instead, maybe you want to create a <code>CharArray.array</code> (mutable string) from an existing <code>string</code>:
<lang sml>val src = "Hello";
<syntaxhighlight lang="sml">val src = "Hello";
val srcCopy = CharArray.array (size src, #"x"); (* 'x' is just dummy character *)
val srcCopy = CharArray.array (size src, #"x"); (* 'x' is just dummy character *)
CharArray.copyVec {src = src, dst = srcCopy, di = 0};
CharArray.copyVec {src = src, dst = srcCopy, di = 0};
src = CharArray.vector srcCopy; (* evaluates to true *)</lang>
src = CharArray.vector srcCopy; (* evaluates to true *)</syntaxhighlight>


or from another <code>CharArray.array</code>:
or from another <code>CharArray.array</code>:
<lang sml>val srcCopy2 = CharArray.array (CharArray.length srcCopy, #"x"); (* 'x' is just dummy character *)
<syntaxhighlight lang="sml">val srcCopy2 = CharArray.array (CharArray.length srcCopy, #"x"); (* 'x' is just dummy character *)
CharArray.copy {src = srcCopy, dst = srcCopy2, di = 0};</lang>
CharArray.copy {src = srcCopy, dst = srcCopy2, di = 0};</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Just use assignment:
Just use assignment:
<lang swift>var src = "Hello"
<syntaxhighlight lang="swift">var src = "Hello"
var dst = src</lang>
var dst = src</syntaxhighlight>
Strings in Swift are value types, so assigning copies the string.
Strings in Swift are value types, so assigning copies the string.


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set src "Rosetta Code"
<syntaxhighlight lang="tcl">set src "Rosetta Code"
set dst $src</lang>
set dst $src</syntaxhighlight>
Tcl copies strings internally when needed.
Tcl copies strings internally when needed.
To be exact, it uses a basic value model based on simple objects that are immutable when shared (i.e., when they have more than one effective reference to them); when unshared, they can be changed because the only holder of a reference has to be the code requesting the change.
To be exact, it uses a basic value model based on simple objects that are immutable when shared (i.e., when they have more than one effective reference to them); when unshared, they can be changed because the only holder of a reference has to be the code requesting the change.
Line 2,385: Line 2,512:


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
<lang ti83b>:"Rosetta Code"→Str1
<syntaxhighlight lang="ti83b">:"Rosetta Code"→Str1
:Str1→Str2</lang>
:Str1→Str2</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
<lang ti89b>:"Rosetta Code"→str1
<syntaxhighlight lang="ti89b">:"Rosetta Code"→str1
:str1→str2</lang>
:str1→str2</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
<lang toka>" hello" is-data a
<syntaxhighlight lang="toka">" hello" is-data a
a string.clone is-data b</lang>
a string.clone is-data b</syntaxhighlight>


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


MainModule : {
MainModule : {
Line 2,410: Line 2,537:
)
)
)
)
}</lang>{{out}}
}</syntaxhighlight>{{out}}
<pre>
<pre>
Good bye!
Good bye!
Line 2,420: Line 2,547:
Strings are immutable character sequences,
Strings are immutable character sequences,
so copying a string just means duplicating the reference at the top of the stack:
so copying a string just means duplicating the reference at the top of the stack:
<lang trith>"Hello" dup</lang>
<syntaxhighlight lang="trith">"Hello" dup</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
str="Hello"
str="Hello"
dst=str</lang>
dst=str</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


<lang bash>foo="Hello"
<syntaxhighlight lang="bash">foo="Hello"
bar=$foo # This is a copy of the string</lang>
bar=$foo # This is a copy of the string</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl string a b
<syntaxhighlight lang="ursa">decl string a b
set a "hello"
set a "hello"
set b a</lang>
set b a</syntaxhighlight>


=={{header|V}}==
=={{header|V}}==
Line 2,441: Line 2,568:
so the string is immutable.
so the string is immutable.


<lang v>"hello" dup</lang>
<syntaxhighlight lang="v">"hello" dup</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
This program copies string in variable a to variable b. Mutating variable a subsequently doesn't alter variable b. Variable b is not a reference.
This program copies string in variable a to variable b. Mutating variable a subsequently doesn't alter variable b. Variable b is not a reference.
<lang vb>Sub copystring()
<syntaxhighlight lang="vb">Sub copystring()
a = "Hello World!"
a = "Hello World!"
b = a
b = a
Line 2,451: Line 2,578:
Debug.Print b
Debug.Print b
Debug.Print a
Debug.Print a
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>Hello World!
<pre>Hello World!
I'm gone</pre>
I'm gone</pre>


=={{header|Vim Script}}==
=={{header|Vim Script}}==
<lang vim>let str1 = "original string"
<syntaxhighlight lang="vim">let str1 = "original string"
let str2 = str1
let str2 = str1
let str1 = "new string"
let str1 = "new string"


echo "String 1:" str1
echo "String 1:" str1
echo "String 2:" str2</lang>
echo "String 2:" str2</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,471: Line 2,598:


{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>'Immutable Strings
<syntaxhighlight lang="vbnet">'Immutable Strings
Dim a = "Test string"
Dim a = "Test string"
Dim b = a 'reference to same string
Dim b = a 'reference to same string
Line 2,479: Line 2,606:
Dim x As New Text.StringBuilder("Test string")
Dim x As New Text.StringBuilder("Test string")
Dim y = x 'reference
Dim y = x 'reference
Dim z = New Text.StringBuilder(x.ToString) 'new string</lang>
Dim z = New Text.StringBuilder(x.ToString) 'new string</syntaxhighlight>


Alternatively, you can use, with all versions of the .NET framework:
Alternatively, you can use, with all versions of the .NET framework:
<lang vbnet>Dim a As String = "Test String"
<syntaxhighlight lang="vbnet">Dim a As String = "Test String"
Dim b As String = String.Copy(a) ' New string</lang>
Dim b As String = String.Copy(a) ' New string</syntaxhighlight>

=={{header|V (Vlang)}}==
Strings in Vlang are immutable. There is no need to distinguish between copying and making an additional reference.
<syntaxhighlight lang="Vlang">
text := "Hello"
copy_of := text
println(copy_of)
</syntaxhighlight>

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


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,489: Line 2,629:


Although technically a reference type, this means there is no need to distinguish between copying the contents of a string and making an additional reference. We can therefore just use assignment to copy a string.
Although technically a reference type, this means there is no need to distinguish between copying the contents of a string and making an additional reference. We can therefore just use assignment to copy a string.
<lang ecmascript>var s = "wren"
<syntaxhighlight lang="wren">var s = "wren"
var t = s
var t = s
System.print("Are 's' and 't' equal? %(s == t)")</lang>
System.print("Are 's' and 't' equal? %(s == t)")</syntaxhighlight>


{{out}}
{{out}}
Line 2,501: Line 2,641:
{{works with|nasm}}
{{works with|nasm}}
creating a second 0 terminated string with the same content:
creating a second 0 terminated string with the same content:
<lang asm>
<syntaxhighlight lang="asm">
section .data
section .data
string db "Hello World", 0
string db "Hello World", 0
Line 2,522: Line 2,662:
xor eax, eax
xor eax, eax
ret
ret
</syntaxhighlight>
</lang>


creating a second string; first byte signals length of string
creating a second string; first byte signals length of string
<lang asm>
<syntaxhighlight lang="asm">
section .data
section .data
string db 11,"Hello World"
string db 11,"Hello World"
Line 2,548: Line 2,688:
xor eax, eax
xor eax, eax
ret
ret
</syntaxhighlight>
</lang>


=={{header|X86-64 Assembly}}==
=={{header|X86-64 Assembly}}==
===UASM 2.52===
===UASM 2.52===
<lang asm>
<syntaxhighlight lang="asm">
option casemap:none
option casemap:none
option literals:on
option literals:on
Line 2,595: Line 2,735:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,602: Line 2,742:
-> dp (0x4030a4) = Goodbye, World!
-> dp (0x4030a4) = Goodbye, World!
-> bytes copied: 15
-> bytes copied: 15
</pre>

===NASM 2.15===
<syntaxhighlight lang="asm">
%macro sysdef 2
%define sys_%1 %2
%endmacro
sysdef write, 1

%macro prolog 1
push rbp
mov rbp, rsp
sub rsp, %1
%endmacro

%macro epilog 1
add rsp, %1
pop rbp
%endmacro

%macro xlea 2
lea %1, [rel %2]
%endmacro

%macro inv 1-7 0,0,0,0,0,0
mov r9,%7
mov r8,%6
mov r10,%5
mov rdx,%4
mov rsi,%3
mov rdi,%2
mov rax,sys_%1
syscall
%endmacro

section .rodata
sz1 db "Goodbye, World!",0xa,0

section .bss
sz2 resq 1

section .text
strlcpy:
prolog 0x38
%define dest rbp-0x18
%define src rbp-0x10
%define n rbp-0x8

mov qword [rbp-0x28], rdi
mov qword [rbp-0x30], rsi
mov qword [rbp-0x38], rdx
mov rax, qword [rbp-0x28]
mov qword [dest], rax
mov rax, qword [rbp-0x30]
mov qword [src], rax
mov rax, qword [rbp-0x38]
mov qword [n], rax
cmp qword [n], 0
je _stlc_done
_stlc_doloop:
dec qword [n]
cmp qword [n], 0
je _stlc_done
mov rbx, qword [src]
lea rax, [rbx+1]
mov qword [src], rax
mov rax, qword [dest]
lea rcx, [rax+1]
mov qword [dest], rcx
movzx ebx, byte [rbx]
mov byte [rax], bl
movzx eax, byte [rax]
test al, al
je _stlc_done
jmp _stlc_doloop
_stlc_done:
epilog 0x38
ret

strlen:
prolog 0x10
%define s rbp-0x8

mov qword [rbp-0x10], rdi
mov rax, qword [rbp-0x10]
mov qword [s], rax
mov rsi, qword [s]
xor rcx, rcx
_stl_count:
cmp byte [rsi+rcx], 0
je _stl_exit
inc rcx
jne _stl_count
_stl_exit:
mov rax, rcx
epilog 0x10
ret

global main
main:
prolog 0x20
%define tmp rbp-0x20
xlea rbx, sz1
mov qword [tmp], rbx
mov rdi, qword [tmp]
call strlen
mov rcx, rax
push rcx
mov rdx, rcx
xlea rsi, sz1
xlea rdi, sz2
call strlcpy
xlea rbx, sz2
pop rcx
inv write, 1, rbx, rcx
inv exit, 0
epilog 0x20
ret
</syntaxhighlight>
{{out}}
<pre>
Goodbye, World!
</pre>
</pre>


Line 2,610: Line 2,872:
The string copy routine from the standard library is shown.
The string copy routine from the standard library is shown.


<lang XPL0>proc StrCopy(A, B); \Copy string: A --> B
<syntaxhighlight lang="xpl0">proc StrCopy(A, B); \Copy string: A --> B
char A, B; \Strings: B must already have enough space "Reserved"
char A, B; \Strings: B must already have enough space "Reserved"
int I; \Beware if strings overlap
int I; \Beware if strings overlap
Line 2,622: Line 2,884:
S2:= S1; \S2 now also points to the string
S2:= S1; \S2 now also points to the string
StrCopy(S1, S3); \S3 points to a separate copy of the string
StrCopy(S1, S3); \S3 points to a separate copy of the string
]</lang>
]</syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
Line 2,628: Line 2,890:
Making an additional reference to a string is easy. If you know the address of the beginning of the string, store that address in RAM somewhere else.
Making an additional reference to a string is easy. If you know the address of the beginning of the string, store that address in RAM somewhere else.


<lang z80>ld hl,MyString
<syntaxhighlight lang="z80">ld hl,MyString
ld (PointerVariable),hl
ld (PointerVariable),hl


Line 2,635: Line 2,897:


PointerVariable:
PointerVariable:
word 0 ;placeholder for the address of the above string, gets written to by the code above.</lang>
word 0 ;placeholder for the address of the above string, gets written to by the code above.</syntaxhighlight>


'''NOTE:''' If you're programming for the Game Boy, you can't store a 16-bit value directly into RAM from <code>HL</code>. There are other methods to achieve the same result, and here's one:
'''NOTE:''' If you're programming for the Game Boy, you can't store a 16-bit value directly into RAM from <code>HL</code>. There are other methods to achieve the same result, and here's one:
<lang z80>ld a,<MyString ; < represents the low byte of the address. Some assemblers use LOW() with the label in the parentheses.
<syntaxhighlight lang="z80">ld a,<MyString ; < represents the low byte of the address. Some assemblers use LOW() with the label in the parentheses.
ld (PointerVariable),a
ld (PointerVariable),a
ld a,>MyString ; > represents the high byte of the address. Some assemblers use HIGH() with the label in the parentheses.
ld a,>MyString ; > represents the high byte of the address. Some assemblers use HIGH() with the label in the parentheses.
ld (PointerVariable+1),a</lang>
ld (PointerVariable+1),a</syntaxhighlight>


===Copying A String===
===Copying A String===
As long as you have enough RAM space to hold the entire string, you can copy it somewhere else in memory. If you know the string's length in advance a simple <code>LDIR</code> will be sufficient. This method will use the null terminator to tell the copy function when to stop:
As long as you have enough RAM space to hold the entire string, you can copy it somewhere else in memory. If you know the string's length in advance a simple <code>LDIR</code> will be sufficient. This method will use the null terminator to tell the copy function when to stop:


<lang z80>StrCpy:
<syntaxhighlight lang="z80">StrCpy:
;input: HL = base address of string you wish to copy
;input: HL = base address of string you wish to copy
; DE = where you want to copy it to.
; DE = where you want to copy it to.
Line 2,657: Line 2,919:
inc hl
inc hl
inc de
inc de
jr StrCpy</lang>
jr StrCpy</syntaxhighlight>

If you're using the "Pascal style" where the string length is prepended before the string itself, you can use this method instead, assuming your string is shorter than 255 bytes in length.
<syntaxhighlight lang="z80">ld hl,myString
ld c,(hl)
ld b,0
inc c
ld de,buffer
ldir ;copies from (HL) to (DE), BC times.
ret

myString:
byte 5 ;len("Hello")
byte "Hello"


buffer:
byte 0
byte 0,0,0,0,0</syntaxhighlight>


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


const debug = std.debug;
const debug = std.debug;
Line 2,682: Line 2,960:
debug.assert(mem.eql(u8, dest1[0..], "A string."));
debug.assert(mem.eql(u8, dest1[0..], "A string."));
debug.assert(mem.eql(u8, dest2[0..], "A string."));
debug.assert(mem.eql(u8, dest2[0..], "A string."));
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Strings are immutable so copy is just return the string:
Strings are immutable so copy is just return the string:
<lang zkl>"abc".copy() // noop</lang>
<syntaxhighlight lang="zkl">"abc".copy() // noop</syntaxhighlight>


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">
module Main;
module Main;
var
var
Line 2,701: Line 2,979:
copy(c,r);writeln(r);
copy(c,r);writeln(r);
end Main.
end Main.
</syntaxhighlight>
</lang>


=={{header|Zoomscript}}==
=={{header|Zoomscript}}==
For typing:
For typing:
<syntaxhighlight lang="zoomscript">var a
<lang Zoomscript>var a
var b
var b
a = "World"
a = "World"
b = a
b = a
a = "Hello"
a = "Hello"
print (a," ",b)</lang>
print (a," ",b)</syntaxhighlight>
For importing:
For importing:


Line 2,717: Line 2,995:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==


<lang basic>10 LET a$ = "Hello": REM a$ is the original string
<syntaxhighlight lang="basic">10 LET a$ = "Hello": REM a$ is the original string
20 LET b$ = a$: REM b$ is the copy</lang>
20 LET b$ = a$: REM b$ is the copy</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
Version 1:
Version 1:
Assign variable "s" to variable "b".
Assign variable "s" to variable "b".
<syntaxhighlight lang="hopper">
<lang Hopper>
#include <hopper.h>
#include <hopper.h>
main:
main:
Line 2,730: Line 3,008:
{s,"\n",t}println
{s,"\n",t}println
exit(0)
exit(0)
</syntaxhighlight>
</lang>
Output:
Output:
string to copy
string to copy
Line 2,737: Line 3,015:
Version 2:
Version 2:
Soft copy to variable (CPY).
Soft copy to variable (CPY).
<syntaxhighlight lang="hopper">
<lang Hopper>
#include <hopper.h>
#include <hopper.h>
main:
main:
Line 2,744: Line 3,022:
{"2:",s}println
{"2:",s}println
exit(0)
exit(0)
</syntaxhighlight>
</lang>
Output:
Output:
1:string to copy
1:string to copy
Line 2,751: Line 3,029:
Version 3:
Version 3:
From stack to var: hard copy (move, MOV).
From stack to var: hard copy (move, MOV).
<syntaxhighlight lang="hopper">
<lang Hopper>
#include <hopper.h>
#include <hopper.h>
main:
main:
Line 2,758: Line 3,036:
{s}println
{s}println
exit(0)
exit(0)
</syntaxhighlight>
</lang>
Output:
Output:
string to copy
string to copy

Latest revision as of 09:33, 21 February 2024

Task
Copy a string
You are encouraged to solve this task according to the task description, using any language you may know.

This task is about copying a string.


Task

Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string.


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

V src = ‘hello’
V dst = copy(src)

360 Assembly

To copy a string, we use an MVC (Move Character). To make a reference to a string, we use a LA (Load Address).

*        Duplicate a string
         MVC    A,=CL64'Hello'     a='Hello'
         MVC    B,A                b=a          memory copy
         MVC    A,=CL64'Goodbye'   a='Goodbye'
         XPRNT  A,L'A              print a
         XPRNT  B,L'B              print b
         ...
*        Make reference to a string a string
         MVC    A,=CL64'Hi!'       a='Hi!'
         LA     R1,A               r1=@a        set pointer
         ST     R1,REFA            refa=@a      store pointer
         XPRNT  A,L'A              print a
         XPRNT  0(R1),L'A          print %refa
         ...
A        DS     CL64               a
B        DS     CL64               b
REFA     DS     A                  @a

6502 Assembly

source equ $10            ;$10 was chosen arbitrarily
source_hi equ source+1    ;the high byte MUST be after the low byte, otherwise this will not work.
dest equ $12
dest_hi equ dest+1

LDA #<MyString ;get the low byte of &MyString
STA source
LDA #>MyString ;get the high byte
STA source_hi  ;we just created a "shallow reference" to an existing string. 
               ;As it turns out, this is a necessary step to do a deep copy.

LDA #<RamBuffer
STA dest
LDA #>RamBuffer
STA dest_hi


strcpy:
;assumes that RamBuffer is big enough to hold the source string, and that the memory ranges do not overlap.
;if you've ever wondered why C's strcpy is considered "unsafe", this is why.

LDY #0
.again:
LDA (source),y
STA (dest),y
BEQ .done
INY
BNE .again   ;exit after 256 bytes copied or the null terminator is reached, whichever occurs first.
RTS

  
MyString:
byte "hello",0
RamBuffer:
byte 0,0,0,0,0,0

68000 Assembly

Making a reference to an existing string is simple. Just load its memory location into an address register.

myString: DC.B "HELLO WORLD",0
EVEN

LEA myString,A3

Copying a string involves a little more work:

StringRam equ $100000

myString: DC.B "HELLO WORLD",0
EVEN

LEA myString,A3
LEA StringRam,A4

CopyString:
MOVE.B (A3)+,D0
MOVE.B D0,(A4)+  ;we could have used "MOVE.B (A3)+,(A4)+" but this makes it easier to check for the terminator.
BEQ Terminated
BRA CopyString

Terminated:      ;the null terminator is already stored along with the string itself, so we are done.
;program ends here.

8086 Assembly

The technique varies depending on whether you just want a new reference to the old string or to actually duplicate it in RAM. Strangely, this is one of the few things that's actually easier to do correctly in assembly than in high-level languages - it's very unlikely you'll do the wrong one by accident.

Making a new reference

This technique is useful if you wish to create a struct/record that needs to be able to retrieve a string quickly. All you need to do is get a pointer to the desired string and store it in RAM.

.model small 
.stack 1024

.data

myString byte "Hello World!",0    ; a null-terminated string

myStruct word 0

.code

mov ax,@data
mov ds,ax       ;load data segment into DS

mov bx,offset myString   ;get the pointer to myString

mov word ptr [ds:myStruct],bx

mov ax,4C00h
int 21h         ;quit program and return to DOS

Creating a "deep copy"

This method will actually make a byte-for-byte copy somewhere else in RAM.

.model small 
.stack 1024

.data

myString byte "Hello World!",0    ; a null-terminated string

StringRam byte 256 dup (0)        ;256 null bytes

.code

mov ax,@data
mov ds,ax       ;load data segment into DS
mov es,ax       ;also load it into ES

mov si,offset myString
mov di,offset StringRam
mov cx,12       ;length of myString
cld             ;make MOVSB auto-increment rather than auto-decrement (I'm pretty sure DOS begins with 
                ;the direction flag cleared but just to be safe)

rep movsb      ;copies 12 bytes from [ds:si] to [es:di]
mov al,0       ;create a null terminator
stosb          ;store at the end. (It's already there since we initialized StringRam to zeroes, but you may need to do this depending
               ;on what was previously stored in StringRam, if you've copied a string there already.

mov ax,4C00h
int 21h         ;quit program and return to DOS

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program copystr64.s   */
 
/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szString: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
.align 4
qPtString:    .skip 8
szString1:    .skip 80
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main:                    // entry of program
 
                         // display start string 
    ldr x0,qAdrszString
    bl affichageMess
                         // copy pointer string
    ldr x0,qAdrszString
    ldr x1,qAdriPtString
    str x0,[x1]
                         // control
    ldr x1,qAdriPtString
    ldr x0,[x1]
    bl affichageMess
                         // copy string
    ldr x0,qAdrszString    
    ldr x1,qAdrszString1
1:
    ldrb w2,[x0],1       // read one byte and increment pointer one byte
    strb w2,[x1],1       // store one byte and increment pointer one byte
    cmp x2,#0            // end of string ?
    bne 1b               // no -> loop 
                         // control
    ldr x0,qAdrszString1
    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
qAdriPtString:       .quad qPtString
qAdrszString1:       .quad szString1
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

ABAP

data: lv_string1 type string value 'Test',
      lv_string2 type string.
lv_string2 = lv_string1.

Inline Declaration

Works with: ABAP version 7.4 Or above only
DATA(string1) = |Test|.
DATA(string2) = string1.

Action!

PROC Main()
  CHAR ARRAY str1,str2,str3(10)
  
  str1="Atari"
  str2=str1 
  SCopy(str3,str1)

  PrintF(" base=%S%E",str1)
  PrintF("alias=%S%E",str2)
  PrintF(" copy=%S%E",str3)
  PutE()

  SCopy(str1,"Action!")

  PrintF(" base=%S%E",str1)
  PrintF("alias=%S%E",str2)
  PrintF(" copy=%S%E",str3)
RETURN
Output:

Screenshot from Atari 8-bit computer

 base=Atari
alias=Atari
 copy=Atari

 base=Action!
alias=Action!
 copy=Atari

ActionScript

Strings are immutable in ActionScript, and can safely be assigned with the assignment operator, much as they can in Java.[1]

var str1:String = "Hello";
var str2:String = str1;

Ada

Ada provides three different kinds of strings. The String type is a fixed length string. The Bounded_String type is a string with variable length up to a specified maximum size. The Unbounded_String type is a variable length string with no specified maximum size. The Bounded_String type behaves a lot like C strings, while the Unbounded_String type behaves a lot like the C++ String class.

Fixed Length String Copying.

Src : String := "Hello";
Dest : String := Src;

Ada provides the ability to manipulate slices of strings.

Src : String := "Rosetta Stone";
Dest : String := Src(1..7); -- Assigns "Rosetta" to Dest
Dest2 : String := Src(9..13); -- Assigns "Stone" to Dest2

Bounded Length String Copying

-- Instantiate the generic package Ada.Strings.Bounded.Generic_Bounded_Length with a maximum length of 80 characters
package Flexible_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
use Flexible_String;

Src : Bounded_String := To_Bounded_String("Hello");
Dest : Bounded_String := Src;

Ada Bounded_String type provides a number of functions for dealing with slices.

Unbounded Length String Copying

-- The package Ada.Strings.Unbounded contains the definition of the Unbounded_String type and all its methods
Src : Unbounded_String := To_Unbounded_String("Hello");
Dest : Unbounded_String := Src;

Aime

The intrinsic text type is immediate, immutable and cannot be referred more than once.

Copying an intrinsic string:

text s, t;
t = "Rosetta";
s = t;

Data of the non intrinsic byte array type can be referred more than once. Copying a binary array of bytes:

data s, t;
# Copy -t- into -s-
b_copy(s, t);
# Set -s- as a reference of the object -t- is pointing
b_set(s, t);
# or:
s = t;

ALGOL 68

In ALGOL 68 strings are simply flexible length arrays of CHAR;

(
  STRING src:="Hello", dest;
  dest:=src
)

ALGOL W

begin
    % strings are (fixed length) values in algol W. Assignment makes a copy   %
    string(10) a, copyOfA;
    a := "some text";
    copyOfA := a;
    % assignment to a will not change copyOfA                                 %
    a := "new value";
    write( a, copyOfA )
end.
Output:
new value some text 

Apex

In Apex, Strings are a primitive data type

String original = 'Test';
String cloned = original;
//"original == cloned" is true

cloned += ' more';
//"original == cloned" is false

AppleScript

set src to "Hello"
set dst to src

ARM Assembly

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

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szString: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"

/* UnInitialized data */
.bss 
.align 4
iPtString:   .skip 4
szString1:    .skip 80

/*  code section */
.text
.global main 
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    @ display start string 
    ldr r0,iAdrszString
    bl affichageMess
    @ copy pointer string
    ldr r0,iAdrszString
    ldr r1,iAdriPtString
    str r0,[r1]
    @ control
    ldr r1,iAdriPtString
    ldr r0,[r1]
    bl affichageMess
    @ copy string
    ldr r0,iAdrszString    
    ldr r1,iAdrszString1
1:
    ldrb r2,[r0],#1   @ read one byte and increment pointer one byte
    strb r2,[r1],#1   @ store one byte and increment pointer one byte
    cmp r2,#0          @ end of string ?
    bne 1b            @ no -> loop 
    @ control
    ldr r0,iAdrszString1
    bl affichageMess

100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszString:		.int szString
iAdriPtString:		.int iPtString
iAdrszString1:		.int szString1

/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */ 
    push {r0,r1,r2,r7}    		/* save others 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" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */ 
    bx lr	        			/* return  */

Arturo

a: new "Hello"
b: a            ; reference the same string

; changing one string in-place
; will change both strings

'b ++ "World"
print b
print a

c: "Hello"
d: new c        ; make a copy of the older string

; changing one string in-place
; will change only the string in question

'd ++ "World"
print d
print c
Output:
HelloWorld
HelloWorld
HelloWorld
Hello

Asymptote

string src, dst;
src = "Hello";
dst = src;
src = " world...";
write(dst, src);

AutoHotkey

src := "Hello"
dst := src

AutoIt

$Src= "Hello"
$dest = $Src

AWK

BEGIN {
  a = "a string"
  b = a
  sub(/a/, "X", a) # modify a
  print b  # b is a copy, not a reference to...
}

Axe

Lbl STRCPY
r₁→S
While {r₂}
 {r₂}→{r₁}
 r₁++
 r₂++
End
0→{r₁}
S
Return

Babel

To copy a string in Babel is the same as copying any other object. Use the cp operator to make a deep-copy.

babel> "Hello, world\n" dup cp dup 0 "Y" 0 1 move8
babel> << <<
Yello, world
Hello, world

BASIC

Works with: QuickBasic version 4.5
Works with: PB version 7.1
 src$ = "Hello"
 dst$ = src$

Applesoft BASIC

100 DEF  FN P(A) =  PEEK (A) +  PEEK(A + 1) * 256 : FOR I =  FN P(105) TO  FN P(107) - 1 STEP 7 : ON PEEK(I + 1) < 128 OR PEEK(I) > 127 GOTO 130 : ON LEFT$(P$, 1) <> CHR$(PEEK(I)) GOTO 130
110 IF LEN(P$) > 1 THEN ON PEEK(I + 1) = 128 GOTO 130 : IF MID$(P$, 2, 1) <> CHR$(PEEK(I + 1) - 128) GOTO 130
120 POKE I + 4, P / 256 : POKE I + 3, P - PEEK(I + 4) * 256 : RETURN
130 NEXT I : STOP
S$ = "HELLO" : REM S$ IS THE ORIGINAL STRING
C$ = S$ : REM C$ IS THE COPY
P$ = "S" : P = 53637 : GOSUB 100"POINT STRING S AT SOMETHING ELSE
?S$
?C$

BaCon

Strings by value or by reference

Strings can be stored by value or by reference. By value means that a copy of the original string is stored in a variable. This happens automatically when when a string variable name ends with the '$' symbol.

Sometimes it may be necessary to refer to a string by reference. In such a case, simply declare a variable name as STRING but omit the '$' at the end. Such a variable will point to the same memory location as the original string. The following examples should show the difference between by value and by reference.

When using string variables by value:

a$ = "I am here"
b$ = a$
a$ = "Hello world..."
PRINT a$, b$

This will print "Hello world...I am here". The variables point to their individual memory areas so they contain different strings. Now consider the following code:

a$ = "Hello world..."
LOCAL b TYPE STRING
b = a$
a$ = "Goodbye..."
PRINT a$, b

This will print "Goodbye...Goodbye..." because the variable 'b' points to the same memory area as 'a$'.

BASIC256

src$ = "Hello"
dst$ = src$
src$ = " world..."
print dst$; src$

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
Works with: PB version 7.1
src$ = "Hello"  ' is the original string
dst$ = src$     ' is the copy
src$ = " world..."
PRINT dst$; src$

True BASIC

Works with: QBasic
Works with: BASIC256
Works with: Yabasic
LET src$ = "Hello"
LET dst$ = src$
LET src$ = " world..."
PRINT dst$; src$
END

Yabasic

src$ = "Hello"
dst$ = src$
src$ = " world..."
print dst$, src$
end

Commodore BASIC

10 A$ = "HELLO"
20 REM COPY CONTENTS OF A$ TO B$
30 B$ = A$
40 REM CHANGE CONTENTS OF A$
50 A$ = "HI"
60 REM DISPLAY CONTENTS
70 PRINT A$, B$

Commodore BASIC can't do pointers or 'reference to'

Sinclair ZX81 BASIC

Creating a new reference to an existing string is not possible, or at least not easy. (You could probably do it with PEEKs and POKEs.) This program demonstrates that an assignment statement copies a string, by showing that the two strings can afterwards be independently modified.

10 LET A$="BECAUSE I DO NOT HOPE TO TURN AGAIN"
20 LET B$=A$
30 LET A$=A$( TO 21)
40 PRINT B$
50 PRINT A$
60 LET B$=A$+B$(22 TO 29)
70 PRINT B$
Output:
BECAUSE I DO NOT HOPE TO TURN AGAIN
BECAUSE I DO NOT HOPE
BECAUSE I DO NOT HOPE TO TURN

Batch File

Since the only variables are environment variables, creating a string copy is fairly straightforward:

set src=Hello
set dst=%src%

BBC BASIC

      source$ = "Hello, world!"
      
      REM Copy the contents of a string:
      copy$ = source$
      PRINT copy$
      
      REM Make an additional reference to a string:
      !^same$ = !^source$
      ?(^same$+4) = ?(^source$+4)
      ?(^same$+5) = ?(^source$+5)
      PRINT same$

Binary Lambda Calculus

In BLC, every value is immutable, including byte-strings. So one never needs to copy them; references are shared.

BQN

BQN strings are character arrays. Like all other types of arrays, they are immutable.

String copying in BQN is left to be defined by the implementation, but CBQN and mlochbaum/BQN(main implementations) copy only the reference until the original source is modified.

a  "Hello"
b  a
•Show ab
a  "hi"
•Show ab
 "Hello" "Hello" 
 "hi" "Hello" 

Bracmat

Because in Bracmat strings are unalterable, you never want to copy a string. Still, you will obtain a copy of a string by overflowing the reference counter of the string. (Currently, reference counters on strings and on most operators are 10 bits wide. The = operator has a much wider 'inexhaustible' reference counter, because it anchors alterable objects.) Still, you won't be able to test whether you got the original or a copy other than by looking at overall memory usage of the Bracmat program at the OS-level or by closely timing comparison operations. You obtain a new reference to a string or a copy of the string by simple assignment using the = or the : operator:

abcdef:?a;
!a:?b;

c=abcdef;
!c:?d;

!a:!b { variables a and b are the same and probably referencing the same string }
!a:!d { variables a and d are also the same but not referencing the same string }

C

#include <stdlib.h>	/* exit(), free() */
#include <stdio.h>	/* fputs(), perror(), printf() */
#include <string.h>

int
main()
{
	size_t len;
	char src[] = "Hello";
	char dst1[80], dst2[80];
	char *dst3, *ref;

	/*
	 * Option 1. Use strcpy() from <string.h>.
	 *
	 * DANGER! strcpy() can overflow the destination buffer.
	 * strcpy() is only safe if the source string is shorter than
	 * the destination buffer. We know that "Hello" (6 characters
	 * with the final '\0') easily fits in dst1 (80 characters).
	 */
	strcpy(dst1, src);

	/*
	 * Option 2. Use strlen() and memcpy() from <string.h>, to copy
	 * strlen(src) + 1 bytes including the final '\0'.
	 */
	len = strlen(src);
	if (len >= sizeof dst2) {
		fputs("The buffer is too small!\n", stderr);
		exit(1);
	}
	memcpy(dst2, src, len + 1);

	/*
	 * Option 3. Use strdup() from <string.h>, to allocate a copy.
	 */
	dst3 = strdup(src);
	if (dst3 == NULL) {
		/* Failed to allocate memory! */
		perror("strdup");
		exit(1);
	}

	/* Create another reference to the source string. */
	ref = src;

	/* Modify the source string, not its copies. */
	memset(src, '-', 5);

	printf(" src: %s\n", src);   /*  src: ----- */
	printf("dst1: %s\n", dst1);  /* dst1: Hello */
	printf("dst2: %s\n", dst2);  /* dst2: Hello */
	printf("dst3: %s\n", dst3);  /* dst3: Hello */
	printf(" ref: %s\n", ref);   /*  ref: ----- */

	/* Free memory from strdup(). */
	free(dst3);

	return 0;
}

Library: BSD libc

#include <stdlib.h>	/* exit() */
#include <stdio.h>	/* fputs(), printf() */
#include <string.h>

int
main()
{
	char src[] = "Hello";
	char dst[80];

	/* Use strlcpy() from <string.h>. */
	if (strlcpy(dst, src, sizeof dst) >= sizeof dst) {
		fputs("The buffer is too small!\n", stderr);
		exit(1);
	}

	memset(src, '-', 5);
	printf("src: %s\n", src);  /* src: ----- */
	printf("dst: %s\n", dst);  /* dst: Hello */

	return 0;
}

Library: Gadget

Versión 2, using Gadget library.

Link:

https://github.com/DanielStuardo/Gadget


#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String v, w = "this message is a message";
   
   Let( v, "Hello world!");
   Print "v = %s\nw = %s\n\n", v,w;
   
   Get_fn_let( v, Upper(w) );
   
   Print "v = %s\nw = %s\n\n", v,w;

   Stack{
       Store ( v, Str_tran_last( Upper(w), "MESSAGE", "PROOF" ) );
   }Stack_off;
   
   Print "v = %s\nw = %s\n\n", v,w;
   
   Free secure v, w;

End
Output:
v = Hello world!
w = this message is a message

v = THIS MESSAGE IS A MESSAGE
w = this message is a message

v = THIS MESSAGE IS A PROOF
w = this message is a message

C#

string src = "Hello";
string dst = src;

C++

#include <iostream>
#include <string>

int main( ) {
   std::string original ("This is the original");
   std::string my_copy = original;
   std::cout << "This is the copy: " << my_copy << std::endl;
   original = "Now we change the original! ";
   std::cout << "my_copy still is " << my_copy << std::endl;
}

Clojure

(let [s "hello"
      s1 s]
  (println s s1))

COBOL

Translation of: C#
MOVE "Hello" TO src
MOVE src TO dst

ColdFusion

In ColdFusion, only complex data types (structs, objects, etc.) are passed by reference. Hence, any string copy operations are by value.

<cfset stringOrig = "I am a string." />
<cfset stringCopy = stringOrig />

Common Lisp

(let* ((s1     "Hello")        ; s1 is a variable containing a string
       (s1-ref s1)             ; another variable with the same value
       (s2     (copy-seq s1))) ; s2 has a distinct string object with the same contents
  (assert (eq s1 s1-ref))      ; same object
  (assert (not (eq s1 s2)))    ; different object
  (assert (equal s1 s2))       ; same contents
                              
  (fill s2 #\!)                ; overwrite s2
  (princ s1)                  
  (princ s2))                  ; will print "Hello!!!!!"

Component Pascal

VAR
	str1: ARRAY 128 OF CHAR;
	str2: ARRAY 32 OF CHAR;
	str3: ARRAY 25 OF CHAR;

...

	str1 := "abcdefghijklmnopqrstuvwxyz";
        str3 := str1; (* don't compile, incompatible assignement *)
        str3 := str1$; (* runtime error, string too long *)
        str2 := str1$; (* OK *)

Computer/zero Assembly

Assuming a string to be a zero-terminated array of bytes, this program takes a string beginning at address src and makes a copy of it beginning at address dest. As an example, we copy the string "Rosetta".

ldsrc:  LDA  src
stdest: STA  dest
        BRZ  done  ; 0-terminated

        LDA  ldsrc
        ADD  one
        STA  ldsrc

        LDA  stdest
        ADD  one
        STA  stdest

        JMP  ldsrc

done:   STP

one:         1

src:         82    ; ASCII
             111
             115
             101
             116
             116
             97
             0

dest:

Crystal

s1 = "Hello"
s2 = s1

D

void main() {
    string src = "This is a string";

    // copy contents:
    auto dest1 = src.idup;

    // copy contents to mutable char array
    auto dest2 = src.dup;

    // copy just the fat reference of the string
    auto dest3 = src;
}

dc

[a string]   # push "a string" on the main stack
d            # duplicate the top value
f            # show the current contents of the main stack
Output:
a string
a string

Delphi

Delphi strings are reference counted with copy on write semantics.

program CopyString;

{$APPTYPE CONSOLE}

var
  s1: string;
  s2: string;
begin
  s1 := 'Goodbye';
  s2 := s1; // S2 points at the same string as S1
  s2 := s2 + ', World!'; // A new string is created for S2

  Writeln(s1);
  Writeln(s2);
end.
Output:
Goodbye
Goodbye, World!

DWScript

DWScript strings are value-type, from the language point of view, you can't have a reference to a String, no more than you can have a reference to an Integer or a Float (unless you wrap in an object of course).

Internally they're transparently implemented via either immutable reference or copy-on-write.

Dyalect

Strings in Dyalect are immutable:

var src = "foobar"
var dst = src

Déjà Vu

In Déjà Vu, strings are immutable, so there really isn't a good reason to copy them. As such, no standard way of doing so is provided. However, one can still create a copy of a string by concatenating it with an empty string.

local :orgininal "this is the original"
local :scopy concat( original "" )
!. scopy
Output:
"this is the original"

E

E is a pass-references-by-value object-oriented language, and strings are immutable, so there is never a need for or benefit from copying a string. Various operations, such as taking the substring (run) from the beginning to the end (someString.run(0)) might create a copy, but this is not guaranteed.

EasyLang

a$ = "hello"
b$ = a$
print b$

EchoLisp

Strings are immutable. A copy will return the same object.

(define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing
     #syntax:string-copy
(define s "abc")
(define t (string-copy s))
    t  "abc"
(eq? s t)  #t ;; same reference, same object

EDSAC order code

Expects the final character of a string to be marked with a 1 in the least significant bit, as in Hello world/Line printer#EDSAC order code. The source string should be loaded at θ+34; it is copied into storage tank 6. The copy is then printed out.

[ Copy a string
  =============

  A program for the EDSAC

  Copies the source string into storage
  tank 6, which is assumed to be free,
  and then prints it from there

  Works with Initial Orders 2 ]

        T56K
        GK

[  0 ]  A34@      [ copy the string ]
[  1 ]  T192F
[  2 ]  H34@
        C32@
        S32@
        E17@
        T31@
        A@
        A33@
        T@
        A1@
        A33@
        T1@
        A2@
        A33@
        T2@
        E@
[ 17 ]  O192F     [ print the copy  ]
[ 18 ]  H192F
        C32@
        S32@
        E30@
        T31@
        A17@
        A33@
        T17@
        A18@
        A33@
        T18@
        E17@
[ 30 ]  ZF
[ 31 ]  PF
[ 32 ]  PD
[ 33 ]  P1F
[ 34 ]  *F
        RF
        OF
        SF
        EF
        TF
        TF
        AF
        !F
        CF
        OF
        DF
        ED

        EZPF
Output:
ROSETTA CODE

Elena

var src := "Hello";
var dst := src;          //  copying the reference
var copy := src.clone(); //  copying the content

Elixir

src = "Hello"
dst = src

Emacs Lisp

(let* ((str1 "hi")
       (str1-ref str1)
       (str2 (copy-sequence str1)))
  (eq str1 str1-ref) ;=> t
  (eq str1 str2) ;=> nil
  (equal str1 str1-ref) ;=> t
  (equal str1 str2)) ;=> t

EMal

in EMal strings are mutable

text original = "Yellow world"
text ref = original # copying the reference
text copied = *original # copying the content
original[0] = "H" # texts are indexable and mutable
original[5] = ","
ref.append("!") # texts are coercible and growable
copied += "?"
^| 
 | original == ref == "Hello, world!"
 | copied == "Yellow world?"
 |^

Erlang

Src = "Hello".
Dst = Src.

Euphoria

Works with: Euphoria version 4.0.3, 4.0.0 RC1 and later

Arrays in many languages are constrained to have a fixed number of elements, and those elements must all be of the same type. Euphoria eliminates both of those restrictions by defining all arrays (sequences) as a list of zero or more Euphoria objects whose element count can be changed at any time. When you retrieve a sequence element, it is not guaranteed to be of any type. You, as a programmer, need to check that the retrieved data is of the type you'd expect, Euphoria will not. The only thing it will check is whether an assignment is legal. For example, if you try to assign a sequence to an integer variable, Euphoria will complain at the time your code does the assignment.

sequence first = "ABC"
sequence newOne = first

F#

.NET strings are immutable, so it is usually not useful to make a deep copy. However if needed, it is possible using a static method of the System.String type:

let str = "hello"
let additionalReference = str
let deepCopy = System.String.Copy( str )

printfn "%b" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true
printfn "%b" <| System.Object.ReferenceEquals( str, deepCopy )            // prints false

Factor

Factor strings are mutable but not growable. Strings will be immutable in a future release.

"This is a mutable string." dup ! reference
"Let's make a deal!" dup clone  ! copy
"New" " string" append .               ! new string
    "New string"

Factor string buffers (sbufs) are mutable and growable.

SBUF" Grow me!" dup "  OK." append
    SBUF" Grow me!  OK."

Convert a string buffer to a string.

SBUF" I'll be a string someday." >string .
    "I'll be a string someday."

Forth

Forth strings are generally stored in memory as prefix counted string, where the first byte contains the string length. However, on the stack they are most often represented as <addr cnt> pairs. Thus the way you copy a string depends on where the source string comes from:

\ Allocate two string buffers
create stringa 256 allot
create stringb 256 allot

\ Copy a constant string into a string buffer
s" Hello" stringa place

\ Copy the contents of one string buffer into another
stringa count  stringb place

Fortran

str2 = str1

Because Fortran uses fixed length character strings if str1 is shorter than str2 then str2 is padded out with trailing spaces. If str1 is longer than str2 it is truncated to fit.

FreeBASIC

' FB 1.05.0 Win64

Dim s As String = "This is a string"
Dim t As String = s
' a separate copy of the string contents has been made as can be seen from the addresses
Print s, StrPtr(s)
Print t, StrPtr(t)
' to refer to the same string a pointer needs to be used
Dim u As String Ptr = @s
Print
Print *u, StrPtr(*u)
Sleep
Output:
This is a string            10623504
This is a string            10623552

This is a string            10623504

Frink

Strings are immutable after construction, so "copying" a string just creates a new reference to a string. All string manipulation routines return a new string.

a = "Monkey"
b = a

FutureBasic

include "NSLog.incl"

CFStringRef original, copy

original = @"Hello!"
copy = fn StringWithString( original )

NSLog( @"%@", copy )

HandleEvents

Output:

Hello!

Gambas

Note that the DIM statement is required in Gambas.

Click this link to run this code

Public Sub main()
Dim src As String
Dim dst As String

src = "Hello"
dst = src

Print src
Print dst
End

GAP

#In GAP strings are lists of characters. An affectation simply copy references
a := "more";
b := a;
b{[1..4]} := "less";
a;
# "less"

# Here is a true copy
a := "more";
b := ShallowCopy(a);
b{[1..4]} := "less";
a;
# "more"

GML

src = "string";
dest = src;

Go

Just use assignment:

src := "Hello"
dst := src

Strings in Go are immutable. Because of this, there is no need to distinguish between copying the contents and making an additional reference. Technically, Go strings are immutable byte slices. A slice is an object that contains a reference to an underlying array. In the assignment shown above, a new slice object is created for dst. Its internal reference is likely to point to the same underlying array as src, but the language does not specify this behavior or make any guarantees about it.

package main

import "fmt"

func main() {
	// creature string
	var creature string = "shark"
	// point to creature
	var pointer *string = &creature
	// creature string
	fmt.Println("creature =", creature) // creature = shark
	// creature location in memory
	fmt.Println("pointer =", pointer) // pointer = 0xc000010210
	// creature through the pointer
	fmt.Println("*pointer =", *pointer) // *pointer = shark
	// set creature through the pointer
	*pointer = "jellyfish"
	// creature through the pointer
	fmt.Println("*pointer =", *pointer) // *pointer = jellyfish
	// creature string
	fmt.Println("creature =", creature) // creature = jellyfish
}

Groovy

The dynamics of references and object creation are very much the same as in Java. However, the meaning of the equality (==) operator is different in Groovy, so we show those differences here, even though they are not relevant to the actual copying.

Example and counter-example:

def string = 'Scooby-doo-bee-doo'    // assigns string object to a variable reference
def stringRef = string               // assigns another variable reference to the same object
def stringCopy = new String(string)  // copies string value into a new object, and assigns to a third variable reference

Test Program:

assert string == stringRef           // they have equal values (like Java equals(), not like Java ==)
assert string.is(stringRef)          // they are references to the same objext (like Java ==)
assert string == stringCopy          // they have equal values
assert ! string.is(stringCopy)       // they are references to different objects (like Java !=)

Caveat Lector: Strings are immutable objects in Groovy, so it is wasteful and utterly unnecessary to ever make copies of them within a Groovy program.

GUISS

Start.Programs,Accessories,Notepad,
Type:Hello world[pling],Highlight:Hello world[pling],
Menu,Edit,Copy,Menu,Edit,Paste

Harbour

cSource := "Hello World"
cDestination := cSource

Haskell

In Haskell, every value is immutable, including Strings. So one never needs to copy them; references are shared.

HicEst

src = "Hello World"
dst = src

i

//Strings are immutable in 'i'.
software {
	a = "Hello World"
	b = a //This copies the string.
	
	a += "s"
	
	print(a)
	print(b)
}

Icon and Unicon

Strings in Icon are immutable.

procedure main()
    a := "qwerty"
    b := a
    b[2+:4] := "uarterl"
    write(a," -> ",b)
end

Under the covers 'b' is created as a reference to the same string as 'a'; the sub-string assignment creates a new copy of the string. However, there is no way to tell this in the language. While most of the time this is transparent, programs that create very long strings through repeated concatenation need to avoid generating intermediate strings. Instead using a list and concatenating at the last minute can perform much better.

Note that strings are indicated using double quotes. However, single quotes are another type called character sets or csets.

J

src  =: 'hello'
dest =: src

J has copy-on-write semantics. So both src and dest are references to the same memory, until src changes, at which time dest retains a copy of the original value of src.

Java

In Java, Strings are immutable, so it doesn't make that much difference to copy it.

String src = "Hello";
String newAlias = src;
String strCopy = new String(src);

//"newAlias == src" is true
//"strCopy == src" is false
//"strCopy.equals(src)" is true

Instead, maybe you want to create a StringBuffer (mutable string) from an existing String or StringBuffer:

StringBuffer srcCopy = new StringBuffer("Hello");

JavaScript

Objects can be copied in JavaScript via simple reassignment. Changes to the properties of one will be reflected in the other:

var container = {myString: "Hello"};
var containerCopy = container; // Now both identifiers refer to the same object

containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"

If you copy property values with reassignment, such as properties of the global object (window in browsers), only the value will be copied and not the reference

var a = "Hello";
var b = a; // Same as saying window.b = window.a

b = "Goodbye" // b contains a copy of a's value and a will still return "Hello"

Joy

"hello" dup

Strings are immutable.

jq

jq is a functional language and all data types, including strings, are immutable. If a string were to be copied (e.g. by exploding and imploding it), the resultant string would be equal in all respects to the original, and from the jq programmer's perspective, the two would be identical.

jq does however have a type of variable, though their values actually don't change -- they are just context-dependent. For example, consider the sequence of steps in the following function:

def demo:
  "abc" as $s    # assignment of a string to a variable
  | $s as $t     # $t points to the same string as $s
  | "def" as $s  # This $s shadows the previous $s
  | $t           # $t still points to "abc"
;

demo
Output:
"abc"

Julia

Strings are immutable in Julia. Assignment of one string valued variable to another is effectively a copy, as subsequent changes to either variable have no effect on the other.

s = "Rosetta Code"
t = s

println("s = \"", s, "\" and, after \"t = s\", t = \"", t, "\"")

s = "Julia at "*s

println("s = \"", s, "\" and, after this change, t = \"", t, "\"")
Output:
s = "Rosetta Code" and, after "t = s", t = "Rosetta Code"
s = "Julia at Rosetta Code" and, after this change, t = "Rosetta Code"

KonsolScript

Var:String str1 = "Hello";
Var:String str2 = str1;

Kotlin

val s = "Hello"
val alias = s      // alias === s
val copy = "" + s  // copy !== s

LabVIEW

In LabVIEW, one can simply wire an input to more than one output.
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lambdatalk

{def S1 hello world}    // set S1 to "hello world"
-> S1
{S1}                    // get the value of S1
-> hello world

{def S2 S1}             // define S2 as S1
-> S2
{S2}                    // the value of S2 is S1
-> S1
{{S2}}                  // get the value of the value of S2 
-> hello world

{def S3 {S1}}           // set S3 to the value of S1 
-> S3
{S3}                    // get the value of S3
-> hello world

Lang5

'hello dup

Lasso

While other datatypes like arrays require ->asCopy & ->asCopyDeep methods, assigning strings creates a copy, not a reference, as is seen below.

local(x = 'I saw a rhino!')
local(y = #x)

#x //I saw a rhino!
'\r'
#y //I saw a rhino!

'\r\r'
#x = 'I saw one too'
#x //I saw one too
'\r'
#y //I saw a rhino!

'\r\r'
#y = 'it was grey.'
#x //I saw one too
'\r'
#y //it was grey.

Latitude

Strings are immutable in Latitude, so it is seldom necessary to explicitly copy one. However, a copy can be distinguished from the original using ===

a := "Hello".
b := a.
c := a clone.
println: a == b.  ; True
println: a == c.  ; True
println: a === b. ; True
println: a === c. ; False

LC3 Assembly

Copying a string is the same as copying any other zero-terminated array. This program copies the string at SRC to COPY, then prints the copy to show it has worked.

        .ORIG      0x3000

        LEA        R1,SRC
        LEA        R2,COPY

LOOP    LDR        R3,R1,0
        STR        R3,R2,0
        BRZ        DONE
        ADD        R1,R1,1
        ADD        R2,R2,1
        BRNZP      LOOP

DONE    LEA        R0,COPY
        PUTS

        HALT

SRC     .STRINGZ   "What, has this thing appeared again tonight?"

COPY    .BLKW      128

        .END
Output:
What, has this thing appeared again tonight?

LFE

(let* ((a '"data assigned to a")
       (b a)) 
  (: io format '"Contents of 'b': ~s~n" (list b)))
Output:
Contents of 'b': data assigned to a

One can also use set to copy a sting when one is in the LFE REPL:

> (set a '"data")
"data"
> a
"data"
> (set b a)
"data"
> b
"data"

Liberty BASIC

src$ = "Hello"
dest$ = src$
print src$
print dest$

Lingo

str = "Hello world!"
str2 = str

Syntax-wise strings are not immuatable in Lingo. You can alter an existing string without new assignment:

put "X" before str
put "X" after str
put "X" into char 6 of str
put str
-- "XHellX world!X"

But memory-wise they are immutable: Lingo internally stores references to strings, and as soon as a string is altered, a new copy is created on the fly, so other references to the original string are not affected by the change.

Lisaac

+ scon : STRING_CONSTANT;
+ svar : STRING;

scon := "sample";
svar := STRING.create 20;
svar.copy scon;
svar.append "!\n";

svar.print;

STRING_CONSTANT is immutable, STRING is not.

Little

string a = "A string";
string b = a;
a =~ s/$/\./; 
puts(a);
puts(b);

LiveCode

put "foo" into bar
put bar into baz
answer bar && baz

Copies are nearly always made, on function calls parameters may be passed by reference (pointer) by prepending @ to a parameter in the function definition, however this is the only case where it is usually performed.

As a functional language, words are normally treated as symbols and cannot be modified. The EQUAL? predicate compares contents instead of identity. In UCB Logo the .EQ predicate tests for "thing" identity.

make "a "foo
make "b "foo
print .eq :a :b   ; true, identical symbols are reused

make "c :a
print .eq :a :c   ; true, copy a reference

make "c word :b "||  ; force a copy of the contents of a word by appending the empty word
print equal? :b :c   ; true
print .eq :b :c     ; false

Lua

Lua strings are immutable, so only one reference to each string exists.

a = "string"
b = a
print(a == b) -->true
print(b) -->string

Maple

In Maple, you cannot really copy a string in the sense that there can be two copies of the string in memory. As soon as you create a second copy of a string that already exists, it get turned into a reference to the first copy. However, you can copy a reference to a string by a simple assignment statement.

> s := "some string";
                           s := "some string"

> t := "some string";
                           t := "some string"

> evalb( s = t ); # they are equal
                                  true

> addressof( s ) = addressof( t ); # not just equal data, but the same address in memory
                        3078334210 = 3078334210

> u := t: # copy reference

Mathematica / Wolfram Language

a="Hello World"
b=a

MATLAB

string1 = 'Hello';
string2 = string1;

Maxima

/* It's possible in Maxima to access individual characters by subscripts, but it's not the usual way.
Also, the result is "Lisp character", which cannot be used by other Maxima functions except cunlisp. The usual
way to access characters is charat, returning a "Maxima character" (actually a one characte string). With the latter,
it's impossible to modify a string in place, thus scopy is of little use. */

a: "loners"$
b: scopy(a)$
c: a$

c[2]: c[5]$

a;
"losers"

b;
"loners"

c;
"losers"

MAXScript

str1 = "Hello"
str2 = copy str1

Metafont

Metafont will always copy a string (does not make references).

string s, a;
s := "hello";
a := s;
s := s & " world";
message s;  % writes "hello world"
message a;  % writes "hello"
end

MiniScript

phrase = "hi"
copy = phrase
print phrase
print copy

MIPS Assembly

This does a full copy of the string, not just copying the pointer to the string's contents.

.data 
	
.text

strcpy:
  addi $sp, $sp, -4
  sw $s0, 0($sp)
  add $s0, $zero, $zero

L1: 
  add $t1, $s0, $a1
  lb $t2, 0($t1)
  add $t3, $s0, $a0
  sb $t2, 0($t3)
  beq $t2, $zero, L2
  addi $s0, $s0, 1
  j L1

L2:
  lw $s0, 0($sp)
  addi $sp, $sp, 4
  jr $ra

Mirah

src = "Hello"
new_alias = src

puts 'interned strings are equal' if src == new_alias

str_copy = String.new(src)
puts 'non-interned strings are not equal' if str_copy != src
puts 'compare strings with equals()' if str_copy.equals(src)

Modula-3

Strings in Modula-3 have the type TEXT.

VAR src: TEXT := "Foo";
VAR dst: TEXT := src;

MUMPS

SET S1="Greetings, Planet"
SET S2=S1

Nanoquery

a = "Hello"
b = a

Neko

var src = "Hello"
var dst = src

Nemerle

Nemerle gives you the option of declaring a variable - even a string - as mutable, so the caveats of languages with only immutable strings don't necessarily apply. However, Nemerle binds the value of the string to the new name when copying; to sort of emulate copying a reference you can use lazy evaluation.

using System;
using System.Console;
using Nemerle;

module StrCopy
{
    Main() : void
    {
        mutable str1 = "I am not changed";      // str1 is bound to literal
        def str2 = lazy(str1);                  // str2 will be bound when evaluated
        def str3 = str1;                        // str3 is bound to value of str1
        str1 = "I am changed";                  // str1 is bound to new literal
        Write($"$(str1)\n$(str2)\n$(str3)\n");  // str2 is bound to value of str1
        // Output: I am changed
        //         I am changed
        //         I am not changed
    }
}

NetRexx

In addition to the string capabilities provided by the Java String libraries (see Java for some examples) NetRexx provides comprehensive string capabilities through the built-in Rexx type. Rexx strings can be copied by simple assignment; as follows:

/* NetRexx */
options replace format comments java crossref symbols nobinary

s1 = 'This is a Rexx string'
s2 = s1

s2 = s2.changestr(' ', '_')

say s1
say s2

In this example a string is created, the string is copied then the copy is modified with the changestr built-in function. Finally both strings are displayed to confirm that the original string wasn't modified by the call to changestr.

Output:
This is a Rexx string
This_is_a_Rexx_string

NewLISP

(define (assert f msg) (if (not f) (println msg)))

(setq  s "Greetings!"  c (copy s))
(reverse c) ; Modifies c in place.

(assert (= s c) "Strings not equal.")

; another way
; Nehal-Singhal 2018-05-25

> (setq a "abcd")
"abcd"
> (setq b a)
"abcd"
> b
"abcd"
> (= a b)
true

Nim

var
  c = "This is a string"
  d = c # Copy c into a new string

NS-HUBASIC

10 A$ = "HELLO"
20 B$ = A$
30 A$ = "HI"
40 PRINT A$, B$

Oberon-2

MODULE CopyString;
TYPE 
	String = ARRAY 128 OF CHAR;
VAR
	a,b: String;

BEGIN
	a := "plain string";
	COPY(a,b);
END CopyString.

Objeck

a := "GoodBye!";
b := a;

Objective-C

Immutable strings - since they are immutable, you may get the same instance with its references count increased. Or, you can get a copy which is mutable if you use mutableCopy. Remember that both copy and mutableCopy return a retained instance. You can also get a copy by doing [NSString stringWithString:] or [[NSString alloc] initWithString:].

Note that both copy and initWithString:/stringWithString: are optimized to return the original string object (possibly retained) if it is immutable.

NSString *original = @"Literal String";
NSString *new = [original copy];
NSString *anotherNew = [NSString stringWithString:original];
NSString *newMutable = [original mutableCopy];

Mutable strings - you can get either new mutable (if you use mutableCopy) or immutable (if you use copy) string:

NSMutableString *original = [NSMutableString stringWithString:@"Literal String"];
NSString *immutable = [original copy];
NSString *anotherImmutable = [NSString stringWithString:original];
NSMutableString *mutable = [original mutableCopy];

Copying a CString into an NSString:

const char *cstring = "I'm a plain C string";
NSString *string = [NSString stringWithUTF8String:cstring];

Copying from data, possibly not null terminated:

char bytes[] = "some data";
NSString *string = [[NSString alloc] initWithBytes:bytes length:9 encoding:NSASCIIStringEncoding];

And of course, if a C string is needed, you can use standard functions like strcpy.

OCaml

let src = "foobar"


Before OCaml 4.02 (2014), strings were mutable and explicit deep copying was needed:

let dst = String.copy src


Between 4.02 and 4.06 (2017), immutable strings were optionally enabled via a flag: -safe-string. A Bytes module was added to provide safe and unsafe mutable views on strings. The two modules were synonymous unless the aforementioned flag was added.

(* Transition-period synonymy between types, explicit type annotations are just for emphasis *)
let dst1 : string = Bytes.copy (src : bytes)
let dst2 : bytes = Bytes.copy (src : string)
(* fails to compile with -safe-string *)


After 4.06, immutable strings became the default, Bytes still exists, but its type is now distinct. The only way to get mutable strings and type synonymy back is at configure-time on the compiler itself.
String.copy issues a deprecation warning, and a (shallow) copy would simply be an assignment by default:

let dst = src

To get a mutable deep-copy still, just convert the string to bytes via Bytes.of_string, which copies for safety, or String.sub/map/init/.. for an immutable copy.

depending on your compiler version, choose the example accordingly.

Octave

str2 = str1

Oforth

To make a copy of the reference, just dup the string

"abcde" dup

There is no need to copy a string content as strings are immutable. If really needed :

StringBuffer new "abcde" <<

Ol

(define a "The String.")

; copy the string
(define b (runes->string (string->runes a)))
(print "a: " a)
(print "b: " b)
(print "b is an a: " (eq? a b))
(print "b same as a: " (equal? a b))

; another way: marshal the string
(define c (fasl-decode (fasl-encode a) #f))
(print "a: " a)
(print "c: " c)
(print "c is an a: " (eq? a c))
(print "c same as a: " (equal? a c))
Output:
a: The String.
b: The String.
b is an a: #false
b same as a: #true
a: The String.
c: The String.
c is an a: #false
c same as a: #true

ooRexx

/* Rexx ***************************************************************
* 16.05.2013 Walter Pachl
**********************************************************************/

s1 = 'This is a Rexx string'
s2 = s1 /* does not copy the string */

Say 's1='s1
Say 's2='s2
i1=s1~identityhash; Say 's1~identityhash='i1
i2=s2~identityhash; Say 's2~identityhash='i2

s2 = s2~changestr('*', '*') /* creates a modified copy */

Say 's1='s1
Say 's2='s2
i1=s1~identityhash; Say 's1~identityhash='i1
i2=s2~identityhash; Say 's2~identityhash='i2
Output:
s1=This is a Rexx string
s2=This is a Rexx string
s1~identityhash=17587366586244
s2~identityhash=17587366586244
s1=This is a Rexx string
s2=This is a Rexx string
s1~identityhash=17587366586244
s2~identityhash=17587366588032

OxygenBasic

string s, t="hello"
s=t

PARI/GP

Assignment in GP always copies.

s1=s

In PARI, strings can be copied and references can be made.

GEN string_copy = gcopy(string);
GEN string_ref = string;

Pascal

See also: Delphi

program copyAString;
	var
		{ The Extended Pascal `string` schema data type
		  is essentially a `packed array[1..capacity] of char`. }
		source, destination: string(80);
	begin
		source := 'Hello world!';
		{ In Pascal _whole_ array data type values can be copied by assignment. }
		destination := source;
		{ Provided `source` is a _non-empty_ string value
		  you can copy in Extended Pascal sub-ranges _of_ _string_ types, too.
		  Note, the sub-range notation is not permitted for a `bindable` data type. }
		destination := source[1..length(source)];
		{ You can also employ Extended Pascal’s `writeStr` routine: }
		writeStr(destination, source);
	end.

Perl

To copy a string, just use ordinary assignment:

my $original = 'Hello.';
my $new = $original;
$new = 'Goodbye.';
print "$original\n";   # prints "Hello."

To create a reference to an existing string, so that modifying the referent changes the original string, use a backslash:

my $original = 'Hello.';
my $ref = \$original;
$$ref = 'Goodbye.';
print "$original\n";   # prints "Goodbye."

If you want a new name for the same string, so that you can modify it without dereferencing a reference, assign a reference to a typeglob:

my $original = 'Hello.';
our $alias;
local *alias = \$original;
$alias = 'Good evening.';
print "$original\n";   # prints "Good evening."

Note that our $alias, though in most cases a no-op, is necessary under stricture. Beware that local binds dynamically, so any subroutines called in this scope will see (and possibly modify!) the value of $alias assigned here.

To make a lexical variable that is an alias of some other variable, the Lexical::Alias module can be used:

use Lexical::Alias;
my $original = 'Hello.';
my $alias;
alias $alias, $original;
$alias = 'Good evening.';
print "$original\n";   # prints "Good evening."

Phix

Library: Phix/basics

Use of strings is utterly intuitive with no unexpected side effects. For example

string one = "feed"
string two = one     -- (two becomes "feed", one remains "feed")
two[2..3] = "oo"     -- (two becomes "food", one remains "feed")
one[1] = 'n'         -- (two remains "food", one becomes "need")
?{one,two}
Output:
{"need","food"}

Phix variables are reference counted (except for integers). When a simple copy is made, it increases the reference count and shares the data, making it very fast on large sequences and long strings. Attempts to modify any data with a reference count greater than one cause a copy to be made, and all other variables are left unchanged. Strings can be modified "in situ", no problem.

PHP

$src = "Hello";
$dst = $src;

Picat

Use copy_term/1 to ensure that the original string is not changed.

go =>
  S1 = "string",
  println(s1=S1),
  S2 = S1,
  S2[1] := 'x', % also changes S1
  println(s1=S1),
  println(s2=S2),
  nl,

  S3 = "string",
  S4 = copy_term(S3),
  S4[1] := 'x', % no change of S3
  println(s3=S3),
  println(s4=S4),

  nl.
Output:
s1 = string
s1 = xtring
s2 = xtring

s3 = string
s4 = xtring


PicoLisp

(setq Str1 "abcdef")
(setq Str2 Str1)                       # Create a reference to that symbol
(setq Str3 (name Str1))                # Create new symbol with name "abcdef"

Pike

int main(){
   string hi = "Hello World.";
   string ih = hi;
}

PL/I

   declare (s1, s2) character (20) varying;
   s1 = 'now is the time';
   s2 = s1;

Pop11

In Pop11 normal data are represented by references, so plain assignment will copy references. To copy data one has to use copy procedure:

vars src, dst;
'Hello' -> src;
copy(src) -> dst;

One can also combine assignment (initialization) with variable declarations:

vars src='Hello';
vars dst=copy(src);

PostScript

In PostScript,

(hello) dup length string copy

PowerShell

Since PowerShell uses .NET behind the scenes and .NET strings are immutable you can simply assign the same string to another variable without breaking anything:

$str = "foo"
$dup = $str

To actually create a copy the Clone() method can be used:

$dup = $str.Clone()

ProDOS

editvar /newvar /value=a /userinput=1 /title=Enter a string to be copied:
editvar /newvar /value=b /userinput=1 /title=Enter current directory of the string:
editvar /newvar /value=c /userinput=1 /title=Enter file to copy to:
copy -a- from -b- to -c-

Prolog

Values in Prolog are immutable so unifying with a variable that already has the value of a string will effectively copy that string. You cannot reassign a value once it has been unified, it is not logical to have a value equal more than one thing.

?- A = "A test string", A = B.
A = B, B = "A test string".

PureBasic

src$ = "Hello"
dst$ = src$

Python

Works with: Python version 2.3, 2.4, and 2.5

Since strings are immutable, all copy operations return the same string, with the reference count increased as appropriate

>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True

To actually copy a string:

>>> a = 'hello'
>>> b = ''.join(a)
>>> a == b
True
>>> b is a  ### Might be True ... depends on "interning" implementation details!
False

As a result of object "interning" some strings such as the empty string and single character strings like 'a' may be references to the same object regardless of copying. This can potentially happen with any Python immutable object and should be of no consequence to any proper code.

Be careful with is - use it only when you want to compare the identity of the object. To compare string values, use the == operator. For numbers and strings any given Python interpreter's implementation of "interning" may cause the object identities to coincide. Thus any number of names to identical numbers or strings might become references to the same objects regardless of how those objects were derived (even if the contents were properly "copied" around). The fact that these are immutable objects makes this a reasonable behavior.


Quackery

Translation of: Joy


Strings are immutable.

$ "hello" dup

R

Copy a string by value:

str1 <- "abc"
str2 <- str1

Racket

#lang racket

(let* ([s1 "Hey"]
       [s2 s1]
       [s3 (string-copy s1)]
       [s4 s3])
  (printf "s1 and s2 refer to ~a strings\n"
          (if (eq? s1 s2) "the same" "different")) ; same
  (printf "s1 and s3 refer to ~a strings\n"
          (if (eq? s1 s3) "the same" "different")) ; different
  (printf "s3 and s4 refer to ~a strings\n"
          (if (eq? s3 s4) "the same" "different")) ; same
  (string-fill! s3 #\!)
  (printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!"

Raku

(formerly Perl 6)

There is no special handling needed to copy a string; just assign it to a new variable:

my $original = 'Hello.';
my $copy = $original;
say $copy;            # prints "Hello."
$copy = 'Goodbye.';
say $copy;            # prints "Goodbye."
say $original;        # prints "Hello."

You can also bind a new variable to an existing one so that each refers to, and can modify the same string.

my $original = 'Hello.';
my $bound := $original;
say $bound;           # prints "Hello."
$bound = 'Goodbye.';
say $bound;           # prints "Goodbye."
say $original;        # prints "Goodbye."


Raven

Copy a string by reference:

'abc' as a
a as b

Copy a string by value:

'abc' as a
a copy as b

REBOL

REBOL [
    Title: "String Copy"
    URL: http://rosettacode.org/wiki/Copy_a_string
]

x: y: "Testing."
y/2: #"X"
print ["Both variables reference same string:" mold x "," mold y]

x: "Slackeriffic!"
print ["Now reference different strings:" mold x "," mold y]

y: copy x        ; String copy here!
y/3: #"X"        ; Modify string.
print ["x copied to y, then modified:" mold x "," mold y]

y: copy/part x 7 ; Copy only the first part of y to x.
print ["Partial copy:" mold x "," mold y]

y: copy/part  skip x 2  3 
print ["Partial copy from offset:" mold x "," mold y]
Output:
Script: "String Copy" (16-Dec-2009)
Both variables reference same string: "TXsting." , "TXsting."
Now reference different strings: "Slackeriffic!" , "TXsting."
x copied to y, then modified: "Slackeriffic!" , "SlXckeriffic!"
Partial copy: "Slackeriffic!" , "Slacker"
Partial copy from offset: "Slackeriffic!" , "ack"

Red

Red[]
originalString: "hello wordl"
copiedString: originalString
; OR
copiedString2: copy originalString

Retro

'this_is_a_string dup s:temp

REXX

The example shows how to copy the contents of one string into another string.

Note that delimiters for literal strings, REXX accepts either of:

  •   '     (an apostrophe)
  •   "     (a double quote)

Also note that   all   REXX values (variables) are stored as (varying length)   character strings.

src = "this is a string"
dst = src

Ring

cStr1 = "Hello!"   # create original string
cStr2 = cStr1      # make new string from original

RLaB

>> s1 = "A string"
A string
>> s2 = s1
A string

Robotic

set "$string1" to "This is a string"
set "$string2" to "$string1"
* "&$string2&"

RPL

Copy a string in stack:

DUP

Copy a string from one variable to another:

"Example" 'STR1' STO
STR1 'STR2' STO

Ruby

In Ruby, String are mutable.

original = "hello"
reference = original          # copies reference
copy1 = original.dup          # instance of original.class
copy2 = String.new(original)  # instance of String

original << " world!"         # append
p reference                   #=> "hello world!"
p copy1                       #=> "hello"
p copy2                       #=> "hello"

There is a method of Object#clone, too, in the copy of the object.

original = "hello".freeze     # prevents further modifications
copy1 = original.dup          # copies contents (without status)
copy2 = original.clone        # copies contents (with status)
p copy1.frozen?               #=> false
p copy1 << " world!"          #=> "hello world!"
p copy2.frozen?               #=> true
p copy2 << " world!"          #=> can't modify frozen String (RuntimeError)

Run BASIC

origString$ = "Hello!"     ' create original string
newString$  = origString$  ' make new strig from original

Rust

fn main() {
    let s1 = "A String";
    let mut s2 = s1;

    s2 = "Another String";

    println!("s1 = {}, s2 = {}", s1, s2);
}

Output:

s1 = A String, s2 = Another String

Sather

class MAIN is
  main is
    s  ::= "a string";
    s1 ::= s;
    -- s1 is a copy
  end;
end;

Scala

  val src = "Hello"
  // Its actually not a copy but a reference
  // That is not a problem because String is immutable
  // In fact its a feature
  val des = src
  assert(src eq des) // Proves the same reference is used. 
  // To make a real copy makes no sense.
  // Actually its hard to make a copy, the compiler is too smart.
  // mkString, toString makes also not a real copy
  val cop = src.mkString.toString
  assert((src eq cop))                 // Still no copyed image
  val copy = src.reverse.reverse       // Finally double reverse makes a copy
  assert(src == copy && !(src eq copy))// Prove, but it really makes no sense.

Scheme

(define dst (string-copy src))

sed

In sed, there are two distinct locations for storing a string: The "pattern space" and the "hold space". The h command copies pattern space to hold space. The g command copies hold space to pattern space.

Seed7

var string: dest is "";

dest := "Hello";

SenseTalk

(* In SenseTalk, assignments normally always make copies of values. *)

put "glorious" into myWord
put myWord into yourWord

(* Assignments can also be made by reference if desired. *)

put a reference to myWord into myRef
set another to refer to myRef

put "ly" after myWord
put "in" before another

put "myWord:   " & myWord
put "yourWord: " & yourWord
put "myRef:    " & myRef
put "another:  " & another
Output:
myWord:   ingloriously
yourWord: glorious
myRef:    ingloriously
another:  ingloriously

Shiny

src: 'hello'
cpy: src

Sidef

var original = "hello";               # new String object
var reference = original;             # points at the original object
var copy1 = String.new(original);     # creates a new String object
var copy2 = original+'';              # ==//==

Simula

BEGIN
    TEXT ORIGINAL, REFERENCE, COPY1;

    ORIGINAL :- "THIS IS CONSTANT TEXT";
    ORIGINAL.SETPOS(1);
    REFERENCE :- ORIGINAL;

! RUN TIME ERROR:
!   ORIGINAL.PUTCHAR('X');
!   "copy-a-string.sim", line 9: ./copy-a-string: Putchar: Constant text object
;

    OUTTEXT(ORIGINAL);
    OUTIMAGE;

    ! CONTENT EQUAL? => T ;
    OUTTEXT(IF ORIGINAL = REFERENCE THEN "T" ELSE "F");
    OUTIMAGE;

    ! SAME TEXT OBJECT? => T ;
    OUTTEXT(IF ORIGINAL == REFERENCE THEN "T" ELSE "F");
    OUTIMAGE;

    COPY1 :- COPY(ORIGINAL);
    COPY1.SETPOS(1);
    COPY1.PUTCHAR('X');
    OUTTEXT(COPY1);
    OUTIMAGE;
END;
Output:
THIS IS CONSTANT TEXT
T
T
XHIS IS CONSTANT TEXT

Slate

[ | :s | s == s copy] applyTo: {'hello'}. "returns False"

Smalltalk

|s1 s2|
"bind the var s1 to the object string on the right"
s1 := 'i am a string'.
"bind the var s2 to the same object..."
s2 := s1.
"bind s2 to a copy of the object bound to s1"
s2 := (s1 copy).

SNOBOL4

* copy a to b
          b = a = "test"
          output = a
          output = b
* change the copy
          b "t" = "T"
          output = b
end
Output:
  test
  test
  Test

Standard ML

In Standard ML, strings are immutable, so you don't copy it.

Instead, maybe you want to create a CharArray.array (mutable string) from an existing string:

val src = "Hello";
val srcCopy = CharArray.array (size src, #"x"); (* 'x' is just dummy character *)
CharArray.copyVec {src = src, dst = srcCopy, di = 0};
src = CharArray.vector srcCopy; (* evaluates to true *)

or from another CharArray.array:

val srcCopy2 = CharArray.array (CharArray.length srcCopy, #"x"); (* 'x' is just dummy character *)
CharArray.copy {src = srcCopy, dst = srcCopy2, di = 0};

Swift

Just use assignment:

var src = "Hello"
var dst = src

Strings in Swift are value types, so assigning copies the string.

Tcl

set src "Rosetta Code"
set dst $src

Tcl copies strings internally when needed. To be exact, it uses a basic value model based on simple objects that are immutable when shared (i.e., when they have more than one effective reference to them); when unshared, they can be changed because the only holder of a reference has to be the code requesting the change. At the script level, this looks like Tcl is making a copy when the variable is assigned as above, but is more efficient in the common case where a value is not actually modified.

TI-83 BASIC

:"Rosetta Code"→Str1
:Str1→Str2

TI-89 BASIC

:"Rosetta Code"→str1
:str1→str2

Toka

" hello" is-data a
a string.clone is-data b

Transd

#lang transd

MainModule : {
  _start: (λ 
    (with s "Hello!" s1 "" s2 ""
        (= s1 s)             // duplication of 's' content
        (rebind s2 s)        // another reference to 's'
        (= s "Good bye!")
        (lout s)
        (lout s1)
        (lout s2)
    )
  )
}
Output:
Good bye!
Hello!
Good bye!

Trith

Strings are immutable character sequences, so copying a string just means duplicating the reference at the top of the stack:

"Hello" dup

TUSCRIPT

$$ MODE TUSCRIPT
str="Hello"
dst=str

UNIX Shell

foo="Hello"
bar=$foo    # This is a copy of the string

Ursa

decl string a b
set a "hello"
set b a

V

dup really makes a reference, but the language is functional, so the string is immutable.

"hello" dup

VBA

This program copies string in variable a to variable b. Mutating variable a subsequently doesn't alter variable b. Variable b is not a reference.

Sub copystring()
    a = "Hello World!"
    b = a
    a = "I'm gone"
    Debug.Print b
    Debug.Print a
End Sub
Output:
Hello World!
I'm gone

Vim Script

let str1 = "original string"
let str2 = str1
let str1 = "new string"

echo "String 1:" str1
echo "String 2:" str2
Output:
String 1: new string                                                            
String 2: original string

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+
'Immutable Strings
Dim a = "Test string"
Dim b = a 'reference to same string
Dim c = New String(a.ToCharArray) 'new string, normally not used

'Mutable Strings
Dim x As New Text.StringBuilder("Test string")
Dim y = x 'reference
Dim z = New Text.StringBuilder(x.ToString) 'new string

Alternatively, you can use, with all versions of the .NET framework:

Dim a As String = "Test String"
Dim b As String = String.Copy(a) ' New string

V (Vlang)

Strings in Vlang are immutable. There is no need to distinguish between copying and making an additional reference.

text := "Hello"
copy_of := text
println(copy_of)
Output:
Hello

Wren

A string in Wren is an immutable array of bytes.

Although technically a reference type, this means there is no need to distinguish between copying the contents of a string and making an additional reference. We can therefore just use assignment to copy a string.

var s = "wren"
var t = s
System.print("Are 's' and 't' equal? %(s == t)")
Output:
Are 's' and 't' equal? true

X86 Assembly

Works with: nasm

creating a second 0 terminated string with the same content:

section .data
    string db "Hello World", 0

section .bss
    string2 resb 12
    
section .text
global _main
_main:
    mov ecx, 0
    looping:
        mov al, [string + ecx]
        mov [string2 + ecx], al
        inc ecx
        cmp al, 0 ;copy until we find the terminating 0
        je end
        jmp looping
    end:
        xor eax, eax
        ret

creating a second string; first byte signals length of string

section .data
    string db 11,"Hello World"

section .bss
    string2 resb 12
    
section .text
global _main
_main:
    xor ecx, ecx ;clear ecx
    mov cl, [string]
    mov [string2], cl ;copy byte signaling length
    mov edx, 1
    looping: ;copy each single byte
        mov al, [string + edx]
        mov [string2 + edx], al
        inc edx
        dec ecx
        cmp ecx, 0
        jg looping
    xor eax, eax
    ret

X86-64 Assembly

UASM 2.52

option casemap:none
option literals:on

printf    proto :dword, :VARARG
exit      proto :dword

.data
  s   db "Goodbye, World!",0

.data?
  d   db 20 dup (?)
  dp  dq ?
  tb  dd ?

.code
main proc
  lea rsi, s                    ;; Put the address of var S into the source index(RSI)
  xor rcx, rcx                  ;; Zero out RCX
  _getsize:
    inc rcx                     ;; Advanced the index by 1
    cmp byte ptr [rsi+rcx],0    ;; check the current byte for terminating 0
    jne _getsize                ;; nope, jump back and check again

  mov tb, ecx                   ;; tb = Total bytes, Keep a copy of the size of the string
  lea rsi, s                    ;; Copy the address of s into the source index(rsi)
  lea rdi, d                    ;; Copy the address of d into the destination index(rdi)
  rep movsb                     ;; Copy bytes from ESI to EDI until RCX is 0
 
  lea rax, s                    ;; Get the address of S
  mov dp, rax                   ;; Copy it from RAX to dp
 
  mov rbx,rdi                   ;; Make a copy of RDI, cause over writes due to ABI call args T_T
  invoke printf, CSTR("-> s (0x%x) = %s",10), rsi, addr s
  invoke printf, CSTR("-> d (0x%x) = %s",10), rbx, addr d
  invoke printf, CSTR("-> dp (0x%x) = %s",10), addr dp, dp
  invoke printf, CSTR("-> bytes copied: %i",10), tb
  xor rsi, rsi
  call exit
  ret 
main endp

end
Output:
-> s (0x40303f) = Goodbye, World!
-> d (0x40309f) = Goodbye, World!
-> dp (0x4030a4) = Goodbye, World!
-> bytes copied: 15

NASM 2.15

%macro sysdef 2
  %define sys_%1    %2
%endmacro
sysdef write,       1

%macro prolog 1
  push rbp
  mov rbp, rsp
  sub rsp, %1
%endmacro

%macro epilog 1
  add rsp, %1
  pop rbp
%endmacro

%macro xlea 2
  lea %1, [rel %2]
%endmacro

%macro inv 1-7 0,0,0,0,0,0
  mov r9,%7
  mov r8,%6
  mov r10,%5
  mov rdx,%4
  mov rsi,%3
  mov rdi,%2
  mov rax,sys_%1
  syscall
%endmacro

section .rodata
sz1     db "Goodbye, World!",0xa,0

section .bss
sz2     resq 1

section .text
  strlcpy:  
    prolog 0x38
    %define dest  rbp-0x18
    %define src   rbp-0x10
    %define n     rbp-0x8

    mov qword [rbp-0x28], rdi
    mov qword [rbp-0x30], rsi
    mov qword [rbp-0x38], rdx
    mov rax, qword [rbp-0x28]
    mov qword [dest], rax
    mov rax, qword [rbp-0x30]
    mov qword [src], rax
    mov rax, qword [rbp-0x38]
    mov qword [n], rax
    cmp qword [n], 0
    je _stlc_done
    _stlc_doloop:
      dec qword [n]
      cmp qword [n], 0
      je _stlc_done
      mov rbx, qword [src]
      lea rax, [rbx+1]
      mov qword [src], rax
      mov rax, qword [dest]
      lea rcx, [rax+1]
      mov qword [dest], rcx
      movzx ebx, byte [rbx]
      mov byte [rax], bl
      movzx eax, byte [rax]
      test al, al
      je _stlc_done
      jmp _stlc_doloop
    _stlc_done:
    epilog 0x38
    ret

  strlen:
    prolog 0x10
    %define s rbp-0x8

    mov qword [rbp-0x10], rdi
    mov rax, qword [rbp-0x10]
    mov qword [s], rax
    mov rsi, qword [s]
    xor rcx, rcx
    _stl_count:
      cmp byte [rsi+rcx], 0
      je _stl_exit
      inc rcx
      jne _stl_count
    _stl_exit:
      mov rax, rcx
    epilog 0x10
    ret

    global main
    main:
      prolog 0x20
      %define tmp rbp-0x20
      xlea rbx, sz1
      mov qword [tmp], rbx
      mov rdi, qword [tmp]
      call strlen
      mov rcx, rax
      push rcx
      mov rdx, rcx
      xlea rsi, sz1
      xlea rdi, sz2
      call strlcpy
      xlea rbx, sz2
      pop rcx
      inv write, 1, rbx, rcx
      inv exit, 0
      epilog 0x20
      ret
Output:
Goodbye, World!

XPL0

The default method of terminating strings is to set the most significant bit of the last character. An alternative is to use the 'string 0' command to specify zero-terminated strings. The string copy routine from the standard library is shown.

proc StrCopy(A, B);     \Copy string: A --> B
char A, B;              \Strings: B must already have enough space "Reserved"
int  I;                 \Beware if strings overlap
for I:= 0 to -1>>1-1 do
    [B(I):= A(I);
    if A(I) >= $80 then return
    ];

char S1, S2, S3(13);
[S1:= "Hello, world!";  \S1 now points to the string
S2:= S1;                \S2 now also points to the string
StrCopy(S1, S3);        \S3 points to a separate copy of the string
]

Z80 Assembly

Making An Additional Reference

Making an additional reference to a string is easy. If you know the address of the beginning of the string, store that address in RAM somewhere else.

ld hl,MyString
ld (PointerVariable),hl

MyString:          ;assembler equates this label to a memory location at compile time
byte "Hello",0

PointerVariable:   
word 0             ;placeholder for the address of the above string, gets written to by the code above.

NOTE: If you're programming for the Game Boy, you can't store a 16-bit value directly into RAM from HL. There are other methods to achieve the same result, and here's one:

ld a,<MyString           ; < represents the low byte of the address. Some assemblers use LOW() with the label in the parentheses.
ld (PointerVariable),a
ld a,>MyString           ; > represents the high byte of the address. Some assemblers use HIGH() with the label in the parentheses.
ld (PointerVariable+1),a

Copying A String

As long as you have enough RAM space to hold the entire string, you can copy it somewhere else in memory. If you know the string's length in advance a simple LDIR will be sufficient. This method will use the null terminator to tell the copy function when to stop:

StrCpy:
;input: HL = base address of string you wish to copy
;       DE = where you want to copy it to.
;       This program assumes that the string is null-terminated, and that there is enough RAM to hold the entire string.

        ld a,(hl)
        or a        ;compare A to 0.
        ret z
        ld (de),a
        inc hl
        inc de
        jr StrCpy

If you're using the "Pascal style" where the string length is prepended before the string itself, you can use this method instead, assuming your string is shorter than 255 bytes in length.

ld hl,myString
ld c,(hl)
ld b,0
inc c
ld de,buffer
ldir  ;copies from (HL) to (DE), BC times.
ret

myString:
byte 5  ;len("Hello")
byte "Hello"

buffer:
byte 0
byte 0,0,0,0,0

Zig

const std = @import("std");

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

test "copy a string" {
    const source = "A string.";

    // Variable `dest1` will have the same type as `source`, which is
    // `*const [9:0]u8`.
    const dest1 = source;

    // Variable `dest2`'s type is [9]u8.
    //
    // The difference between the two is that `dest1` string is null-terminated,
    // while `dest2` is not.
    var dest2: [source.len]u8 = undefined;
    mem.copy(u8, dest2[0..], source[0..]);

    debug.assert(mem.eql(u8, dest1[0..], "A string."));
    debug.assert(mem.eql(u8, dest2[0..], "A string."));
}

zkl

Strings are immutable so copy is just return the string:

"abc".copy()  // noop

zonnon

module Main;
var
	s,r: string;
	c: array 60 of char;
begin
	s := "plain string";r := s; writeln(s);
	(* copy string to array of char *)
	copy(s,c);c[0] := 'P';
	(* copy array of char to string *)
	copy(c,r);writeln(r);
end Main.

Zoomscript

For typing:

var a
var b
a = "World"
b = a
a = "Hello"
print (a," ",b)

For importing:

¶0¶var a¶0¶var b¶0¶a = "World"¶0¶b = a¶0¶a = "Hello"¶0¶print (a," ",b)

ZX Spectrum Basic

10 LET a$ = "Hello": REM a$ is the original string
20 LET b$ = a$: REM b$ is the copy

Amazing Hopper

Version 1: Assign variable "s" to variable "b".

#include <hopper.h>
main:
   s = "string to copy"
   t = s
   {s,"\n",t}println
exit(0)

Output:

  string to copy
  string to copy

Version 2: Soft copy to variable (CPY).

#include <hopper.h>
main:
   s=""
   {"1:","string to copy"},cpy(s),println
   {"2:",s}println
exit(0)

Output:

  1:string to copy
  2:string to copy

Version 3: From stack to var: hard copy (move, MOV).

#include <hopper.h>
main:
   s=""
   {"string to copy"},mov(s)
   {s}println
exit(0)

Output:

  string to copy