Copy a string: Difference between revisions

add string copy for BLC
No edit summary
imported>Tromp
(add string copy for BLC)
 
(36 intermediate revisions by 22 users not shown)
Line 17:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">V src = ‘hello’
V dst = copy(src)</langsyntaxhighlight>
 
=={{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).
<langsyntaxhighlight lang="360asm">* Duplicate a string
MVC A,=CL64'Hello' a='Hello'
MVC B,A b=a memory copy
Line 38:
A DS CL64 a
B DS CL64 b
REFA DS A @a</langsyntaxhighlight>
=={{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}}==
Making a reference to an existing string is simple. Just load its memory location into an address register.
<syntaxhighlight lang="68000devpac">myString: DC.B "HELLO WORLD",0
EVEN
 
LEA myString,A3</syntaxhighlight>
 
Copying a string involves a little more work:
<syntaxhighlight lang="68000devpac">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.</syntaxhighlight>
 
=={{header|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.
 
<syntaxhighlight lang="asm">.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</syntaxhighlight>
 
===Creating a "deep copy"===
This method will actually make a byte-for-byte copy somewhere else in RAM.
 
<syntaxhighlight lang="asm">.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</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program copystr64.s */
Line 105 ⟶ 225:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">data: lv_string1 type string value 'Test',
lv_string2 type string.
lv_string2 = lv_string1.</langsyntaxhighlight>
 
===Inline Declaration===
{{works with|ABAP|7.4 Or above only}}
 
<langsyntaxhighlight ABAPlang="abap">DATA(string1) = |Test|.
DATA(string2) = string1.</langsyntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Copy_a_string.png Screenshot from Atari 8-bit computer]
<pre>
base=Atari
alias=Atari
copy=Atari
 
base=Action!
alias=Action!
copy=Atari
</pre>
 
=={{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]
<langsyntaxhighlight ActionScriptlang="actionscript">var str1:String = "Hello";
var str2:String = str1;</langsyntaxhighlight>
 
=={{header|Ada}}==
Line 131 ⟶ 282:
 
===Fixed Length String Copying.===
<langsyntaxhighlight lang="ada">Src : String := "Hello";
Dest : String := Src;</langsyntaxhighlight>
Ada provides the ability to manipulate slices of strings.
<langsyntaxhighlight lang="ada">Src : String := "Rosetta Stone";
Dest : String := Src(1..7); -- Assigns "Rosetta" to Dest
Dest2 : String := Src(9..13); -- Assigns "Stone" to Dest2</langsyntaxhighlight>
 
===Bounded Length String Copying===
<langsyntaxhighlight 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);
use Flexible_String;
 
Src : Bounded_String := To_Bounded_String("Hello");
Dest : Bounded_String := Src;</langsyntaxhighlight>
Ada Bounded_String type provides a number of functions for dealing with slices.
 
=== Unbounded Length String Copying===
<langsyntaxhighlight 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");
Dest : Unbounded_String := Src;</langsyntaxhighlight>
 
=={{header|Aime}}==
Line 157 ⟶ 308:
 
Copying an intrinsic string:
<langsyntaxhighlight lang="aime">text s, t;
t = "Rosetta";
s = t;</langsyntaxhighlight>
Data of the non intrinsic byte array type can be referred more than once.
Copying a binary array of bytes:
<langsyntaxhighlight lang="aime">data s, t;
# Copy -t- into -s-
b_copy(s, t);
Line 169 ⟶ 320:
# or:
s = t;
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
In ALGOL 68 strings are simply flexible length arrays of CHAR;
 
<langsyntaxhighlight lang="algol68">(
STRING src:="Hello", dest;
dest:=src
)</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% strings are (fixed length) values in algol W. Assignment makes a copy %
string(10) a, copyOfA;
Line 188 ⟶ 339:
a := "new value";
write( a, copyOfA )
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 196 ⟶ 347:
=={{header|Apex}}==
In Apex, Strings are a primitive data type
<langsyntaxhighlight lang="apex">String original = 'Test';
String cloned = original;
//"original == cloned" is true
 
cloned += ' more';
//"original == cloned" is false</langsyntaxhighlight>
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">set src to "Hello"
set dst to src</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program copystr.s */
Line 288 ⟶ 439:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">a: new "Hello"
b: a ; reference the same string
 
Line 310 ⟶ 461:
'd ++ "World"
print d
print c</langsyntaxhighlight>
 
{{out}}
Line 318 ⟶ 469:
HelloWorld
Hello</pre>
 
=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">string src, dst;
src = "Hello";
dst = src;
src = " world...";
write(dst, src);</syntaxhighlight>
 
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight lang="autohotkey">src := "Hello"
dst := src</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
<langsyntaxhighlight lang="autoit">$Src= "Hello"
$dest = $Src</langsyntaxhighlight>
 
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">BEGIN {
a = "a string"
b = a
sub(/a/, "X", a) # modify a
print b # b is a copy, not a reference to...
}</langsyntaxhighlight>
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">Lbl STRCPY
r₁→S
While {r₂}
Line 348 ⟶ 506:
0→{r₁}
S
Return</langsyntaxhighlight>
 
=={{header|Babel}}==
Line 354 ⟶ 512:
To copy a string in Babel is the same as copying any other object. Use the cp operator to make a deep-copy.
 
<langsyntaxhighlight lang="babel">babel> "Hello, world\n" dup cp dup 0 "Y" 0 1 move8
babel> << <<
Yello, world
Hello, world
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 367 ⟶ 525:
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="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
120 POKE I + 4, P / 256 : POKE I + 3, P - PEEK(I + 4) * 256 : RETURN
130 NEXT I : STOP</langsyntaxhighlight>
 
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">S$ = "HELLO" : REM S$ IS THE ORIGINAL STRING
C$ = S$ : REM C$ IS THE COPY</langsyntaxhighlight>
 
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">P$ = "S" : P = 53637 : GOSUB 100"POINT STRING S AT SOMETHING ELSE
?S$
?C$</langsyntaxhighlight>
 
==={{header|BaCon}}===
Line 388 ⟶ 546:
When using string variables by value:
 
<langsyntaxhighlight lang="freebasic">a$ = "I am here"
b$ = a$
a$ = "Hello world..."
PRINT a$, b$</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="freebasic">a$ = "Hello world..."
LOCAL b TYPE STRING
b = a$
a$ = "Goodbye..."
PRINT a$, b</langsyntaxhighlight>
 
This will print "Goodbye...Goodbye..." because the variable 'b' points to the same memory area as 'a$'.
 
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">src$ = "Hello"
dst$ = src$
src$ = " world..."
print dst$; src$</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|PB|7.1}}
<syntaxhighlight lang="qbasic">src$ = "Hello" ' is the original string
dst$ = src$ ' is the copy
src$ = " world..."
PRINT dst$; src$</syntaxhighlight>
 
==={{header|True BASIC}}===
{{works with|QBasic}}
{{works with|BASIC256}}
{{works with|Yabasic}}
<syntaxhighlight lang="qbasic">LET src$ = "Hello"
LET dst$ = src$
LET src$ = " world..."
PRINT dst$; src$
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">src$ = "Hello"
dst$ = src$
src$ = " world..."
print dst$, src$
end</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="basic">10 A$ = "HELLO"
20 REM COPY CONTENTS OF A$ TO B$
30 B$ = A$
Line 410 ⟶ 600:
50 A$ = "HI"
60 REM DISPLAY CONTENTS
70 PRINT A$, B$</langsyntaxhighlight>
Commodore BASIC can't do pointers or 'reference to'
 
==={{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.
<langsyntaxhighlight lang="basic">10 LET A$="BECAUSE I DO NOT HOPE TO TURN AGAIN"
20 LET B$=A$
30 LET A$=A$( TO 21)
Line 421 ⟶ 611:
50 PRINT A$
60 LET B$=A$+B$(22 TO 29)
70 PRINT B$</langsyntaxhighlight>
{{out}}
<pre>BECAUSE I DO NOT HOPE TO TURN AGAIN
Line 430 ⟶ 620:
Since the only variables are environment variables,
creating a string copy is fairly straightforward:
<langsyntaxhighlight lang="dos">set src=Hello
set dst=%src%</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> source$ = "Hello, world!"
REM Copy the contents of a string:
Line 445 ⟶ 635:
?(^same$+4) = ?(^source$+4)
?(^same$+5) = ?(^source$+5)
PRINT same$</langsyntaxhighlight>
 
=={{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}}==
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.
<syntaxhighlight lang="bqn">a ← "Hello"
b ← a
•Show a‿b
a ↩ "hi"
•Show a‿b</syntaxhighlight><syntaxhighlight lang="bqn">⟨ "Hello" "Hello" ⟩
⟨ "hi" "Hello" ⟩</syntaxhighlight>
 
=={{header|Bracmat}}==
Line 454 ⟶ 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.
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:
<langsyntaxhighlight lang="bracmat">abcdef:?a;
!a:?b;
 
Line 462 ⟶ 667:
!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 }
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h> /* exit(), free() */
#include <stdio.h> /* fputs(), perror(), printf() */
#include <string.h>
Line 524 ⟶ 729:
 
return 0;
}</langsyntaxhighlight>
 
==={{libheader|BSD libc}}===
<langsyntaxhighlight lang="c">#include <stdlib.h> /* exit() */
#include <stdio.h> /* fputs(), printf() */
#include <string.h>
Line 548 ⟶ 753:
 
return 0;
}</langsyntaxhighlight>
 
==={{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#}}==
<langsyntaxhighlight lang="csharp">string src = "Hello";
string dst = src;</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
 
Line 564 ⟶ 816:
original = "Now we change the original! ";
std::cout << "my_copy still is " << my_copy << std::endl;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">(let [s "hello"
s1 s]
(println s s1))</langsyntaxhighlight>
 
=={{header|COBOL}}==
{{trans|C#}}
<langsyntaxhighlight cobollang="cobolfree">MOVE "Hello" TO src
MOVE src TO dst</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
Line 582 ⟶ 834:
Hence, any string copy operations are by value.
 
<langsyntaxhighlight lang="coldfusion"><cfset stringOrig = "I am a string." />
<cfset stringCopy = stringOrig /></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="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
Line 596 ⟶ 848:
(fill s2 #\!) ; overwrite s2
(princ s1)
(princ s2)) ; will print "Hello!!!!!"</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
<langsyntaxhighlight lang="oberon2">
VAR
str1: ARRAY 128 OF CHAR;
str2: ARRAY 32 OF CHAR;
str3: ARRAY 25 OF CHAR;
</syntaxhighlight>
</lang>
...
<langsyntaxhighlight lang="oberon2">
str1 := "abcdefghijklmnopqrstuvwxyz";
str3 := str1; (* don't compile, incompatible assignement *)
str3 := str1$; (* runtime error, string too long *)
str2 := str1$; (* OK *)
</syntaxhighlight>
</lang>
 
=={{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".
<langsyntaxhighlight lang="czasm">ldsrc: LDA src
stdest: STA dest
BRZ done ; 0-terminated
Line 642 ⟶ 894:
0
 
dest:</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">s1 = "Hello"
s2 = s1</langsyntaxhighlight>
 
=={{header|D}}==
 
<langsyntaxhighlight lang="d">void main() {
string src = "This is a string";
 
Line 661 ⟶ 913:
// copy just the fat reference of the string
auto dest3 = src;
}</langsyntaxhighlight>
 
=={{header|dc}}==
<langsyntaxhighlight lang="dc">[a string] # push "a string" on the main stack
d # duplicate the top value
f # show the current contents of the main stack</langsyntaxhighlight>
 
{{Out}}
Line 676 ⟶ 928:
Delphi strings are reference counted with [[wp:Copy-on-write|copy on write]] semantics.
 
<langsyntaxhighlight Delphilang="delphi">program CopyString;
 
{$APPTYPE CONSOLE}
Line 690 ⟶ 942:
Writeln(s1);
Writeln(s2);
end.</langsyntaxhighlight>
 
{{out}}
Line 709 ⟶ 961:
Strings in Dyalect are immutable:
 
<langsyntaxhighlight lang="dyalect">var src = "foobar"
var dst = src</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
Line 718 ⟶ 970:
However, one can still create a copy of a string
by concatenating it with an empty string.
<langsyntaxhighlight lang="dejavu">local :orgininal "this is the original"
local :scopy concat( original "" )
!. scopy</langsyntaxhighlight>
{{out}}
<pre>"this is the original"</pre>
Line 732 ⟶ 984:
=={{header|EasyLang}}==
 
<syntaxhighlight lang>a$ = "hellotext">
ba$ = a$</lang>"hello"
b$ = a$
print b$
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Strings are immutable. A copy will return the same object.
<langsyntaxhighlight lang="scheme">
(define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing
→ #syntax:string-copy
Line 744 ⟶ 999:
t → "abc"
(eq? s t) → #t ;; same reference, same object
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="edsac">[ Copy a string
=============
 
Line 810 ⟶ 1,065:
ED
 
EZPF</langsyntaxhighlight>
{{out}}
<pre>ROSETTA CODE</pre>
 
=={{header|Elena}}==
<langsyntaxhighlight lang="elena">
var src := "Hello";
var dst := src; // copying the reference
var copy := src.clone(); // copying the content
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">src = "Hello"
dst = src</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
 
<lang Lisp>
<syntaxhighlight lang="lisp">(setqlet* ((str1 "hi")
(setq str2 (str1-ref str1)
(str2 (copy-sequence str1)))
(eq str1 str2)</lang>
(eq str1 str1-ref) ;=> t
(eq str1 str2) ;=> nil
(equal str1 str1-ref) ;=> t
(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}}==
<langsyntaxhighlight lang="erlang">Src = "Hello".
Dst = Src.</langsyntaxhighlight>
 
=={{header|Euphoria}}==
Line 847 ⟶ 1,122:
Euphoria will complain at the time your code does the assignment.
 
<langsyntaxhighlight Euphorialang="euphoria">sequence first = "ABC"
sequence newOne = first</langsyntaxhighlight>
 
=={{header|F Sharp|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 <code>System.String</code> type:
<langsyntaxhighlight lang="fsharp">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</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 865 ⟶ 1,140:
Strings will be immutable in a future release.
 
<langsyntaxhighlight lang="factor">"This is a mutable string." dup ! reference
"Let's make a deal!" dup clone ! copy
"New" " string" append . ! new string
"New string"</langsyntaxhighlight>
 
Factor string buffers (sbufs) are mutable and growable.
 
<langsyntaxhighlight lang="factor">SBUF" Grow me!" dup " OK." append
SBUF" Grow me! OK."</langsyntaxhighlight>
 
Convert a string buffer to a string.
 
<langsyntaxhighlight lang="factor">SBUF" I'll be a string someday." >string .
"I'll be a string someday."</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 887 ⟶ 1,162:
Thus the way you copy a string depends on where the source string comes from:
 
<langsyntaxhighlight lang="forth">\ Allocate two string buffers
create stringa 256 allot
create stringb 256 allot
Line 895 ⟶ 1,170:
 
\ Copy the contents of one string buffer into another
stringa count stringb place</langsyntaxhighlight>
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">str2 = str1</langsyntaxhighlight>
 
Because Fortran uses fixed length character strings if str1 is shorter than str2 then str2 is padded out with trailing spaces.
Line 905 ⟶ 1,180:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim s As String = "This is a string"
Line 916 ⟶ 1,191:
Print
Print *u, StrPtr(*u)
Sleep</langsyntaxhighlight>
 
{{out}}
Line 928 ⟶ 1,203:
=={{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.
<langsyntaxhighlight lang="frink">
a = "Monkey"
b = a
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="text">
include "ConsoleWindowNSLog.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:
<pre>
"Hello!"
</pre>
 
Line 953 ⟶ 1,232:
 
'''[https://gambas-playground.proko.eu/?gist=b88224f45b9b5be09eafdf069b059076 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub main()
Dim src As String
Dim dst As String
Line 962 ⟶ 1,241:
Print src
Print dst
End</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">#In GAP strings are lists of characters. An affectation simply copy references
a := "more";
b := a;
Line 977 ⟶ 1,256:
b{[1..4]} := "less";
a;
# "more"</langsyntaxhighlight>
 
=={{header|GML}}==
<langsyntaxhighlight GMLlang="gml">src = "string";
dest = src;</langsyntaxhighlight>
 
=={{header|Go}}==
Just use assignment:
<langsyntaxhighlight lang="go">src := "Hello"
dst := src</langsyntaxhighlight>
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.
Line 994 ⟶ 1,273:
but the language does not specify this behavior or make any guarantees about it.
 
::<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,015 ⟶ 1,294:
// creature string
fmt.Println("creature =", creature) // creature = jellyfish
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Line 1,022 ⟶ 1,301:
 
Example and counter-example:
<langsyntaxhighlight 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 stringCopy = new String(string) // copies string value into a new object, and assigns to a third variable reference</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight 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 == stringCopy // they have equal values
assert ! string.is(stringCopy) // they are references to different objects (like Java !=)</langsyntaxhighlight>
 
'''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,036 ⟶ 1,315:
=={{header|GUISS}}==
 
<langsyntaxhighlight lang="guiss">Start.Programs,Accessories,Notepad,
Type:Hello world[pling],Highlight:Hello world[pling],
Menu,Edit,Copy,Menu,Edit,Paste</langsyntaxhighlight>
 
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">cSource := "Hello World"
cDestination := cSource</syntaxhighlight>
 
=={{header|Haskell}}==
Line 1,046 ⟶ 1,329:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">src = "Hello World"
dst = src</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">//Strings are immutable in 'i'.
software {
a = "Hello World"
Line 1,060 ⟶ 1,343:
print(b)
}
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Strings in Icon are immutable.
<langsyntaxhighlight lang="icon">procedure main()
a := "qwerty"
b := a
b[2+:4] := "uarterl"
write(a," -> ",b)
end</langsyntaxhighlight>
 
Under the covers 'b' is created as a reference to the same string as 'a';
Line 1,081 ⟶ 1,364:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">src =: 'hello'
dest =: src</langsyntaxhighlight>
 
J has copy-on-write semantics.
Line 1,089 ⟶ 1,372:
=={{header|Java}}==
In Java, Strings are immutable, so it doesn't make that much difference to copy it.
<langsyntaxhighlight lang="java">String src = "Hello";
String newAlias = src;
String strCopy = new String(src);
Line 1,095 ⟶ 1,378:
//"newAlias == src" is true
//"strCopy == src" is false
//"strCopy.equals(src)" is true</langsyntaxhighlight>
 
Instead, maybe you want to create a <code>StringBuffer</code> (mutable string) from an existing String or StringBuffer:
<langsyntaxhighlight lang="java">StringBuffer srcCopy = new StringBuffer("Hello");</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Objects can be copied in JavaScript via simple reassignment.
Changes to the properties of one will be reflected in the other:
<langsyntaxhighlight lang="javascript">var container = {myString: "Hello"};
var containerCopy = container; // Now both identifiers refer to the same object
 
containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye"</langsyntaxhighlight>
 
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
<langsyntaxhighlight lang="javascript">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"</langsyntaxhighlight>
 
=={{header|Joy}}==
<langsyntaxhighlight lang="joy">"hello" dup</langsyntaxhighlight>
 
Strings are immutable.
Line 1,122 ⟶ 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 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:<langsyntaxhighlight lang="jq">def demo:
"abc" as $s # assignment of a string to a variable
| $s as $t # $t points to the same string as $s
Line 1,130 ⟶ 1,413:
 
demo
</syntaxhighlight>
</lang>
{{Out}}
"abc"
Line 1,136 ⟶ 1,419:
=={{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.
<syntaxhighlight lang="julia">
<lang Julia>
s = "Rosetta Code"
t = s
Line 1,145 ⟶ 1,428:
 
println("s = \"", s, "\" and, after this change, t = \"", t, "\"")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,154 ⟶ 1,437:
 
=={{header|KonsolScript}}==
<langsyntaxhighlight KonsolScriptlang="konsolscript">Var:String str1 = "Hello";
Var:String str2 = str1;</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">val s = "Hello"
val alias = s // alias === s
val copy = "" + s // copy !== s</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
In LabVIEW, one can simply wire an input to more than one output.<br/>
{{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}}==
<syntaxhighlight lang ="lang5">'hello dup</langsyntaxhighlight>
 
=={{header|Lasso}}==
While other datatypes like arrays require ->asCopy & ->asCopyDeep methods,
assigning strings creates a copy, not a reference, as is seen below.
<langsyntaxhighlight Lassolang="lasso">local(x = 'I saw a rhino!')
local(y = #x)
 
Line 1,189 ⟶ 1,492:
#x //I saw one too
'\r'
#y //it was grey.</langsyntaxhighlight>
 
=={{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>
<langsyntaxhighlight lang="latitude">a := "Hello".
b := a.
c := a clone.
Line 1,199 ⟶ 1,502:
println: a == c. ; True
println: a === b. ; True
println: a === c. ; False</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="lc3asm"> .ORIG 0x3000
 
LEA R1,SRC
Line 1,224 ⟶ 1,527:
COPY .BLKW 128
 
.END</langsyntaxhighlight>
{{out}}
<pre>What, has this thing appeared again tonight?</pre>
Line 1,230 ⟶ 1,533:
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">(let* ((a '"data assigned to a")
(b a))
(: io format '"Contents of 'b': ~s~n" (list b)))</langsyntaxhighlight>
 
{{out}}
Line 1,241 ⟶ 1,544:
One can also use <code>set</code> to copy a sting when one is in the LFE REPL:
 
<langsyntaxhighlight lang="lisp">> (set a '"data")
"data"
> a
Line 1,248 ⟶ 1,551:
"data"
> b
"data"</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">src$ = "Hello"
dest$ = src$
print src$
print dest$
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">str = "Hello world!"
str2 = str</langsyntaxhighlight>
 
Syntax-wise strings are not immuatable in Lingo. You can alter an existing string without new assignment:
 
<langsyntaxhighlight lang="lingo">put "X" before str
put "X" after str
put "X" into char 6 of str
put str
-- "XHellX world!X"</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight Lisaaclang="lisaac">+ scon : STRING_CONSTANT;
+ svar : STRING;
 
Line 1,280 ⟶ 1,583:
svar.append "!\n";
 
svar.print;</langsyntaxhighlight>
STRING_CONSTANT is immutable, STRING is not.
 
=={{header|Little}}==
<langsyntaxhighlight Clang="c">string a = "A string";
string b = a;
a =~ s/$/\./;
puts(a);
puts(b);</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put "foo" into bar
put bar into baz
answer bar && baz</langsyntaxhighlight>
 
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,299 ⟶ 1,602:
=={{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.
<langsyntaxhighlight lang="logo">make "a "foo
make "b "foo
print .eq :a :b ; true, identical symbols are reused
Line 1,308 ⟶ 1,611:
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</langsyntaxhighlight>
 
=={{header|Lua}}==
Lua strings are immutable, so only one reference to each string exists.
<langsyntaxhighlight lang="lua">
a = "string"
b = a
print(a == b) -->true
print(b) -->string</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="maple">
<lang Maple>
> s := "some string";
s := "some string"
Line 1,334 ⟶ 1,637:
 
> u := t: # copy reference
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">a="Hello World"
b=a</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">string1 = 'Hello';
string2 = string1;</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight 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
way to access characters is charat, returning a "Maxima character" (actually a one characte string). With the latter,
Line 1,363 ⟶ 1,666:
 
c;
"losers"</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">str1 = "Hello"
str2 = copy str1</langsyntaxhighlight>
 
=={{header|Metafont}}==
Line 1,373 ⟶ 1,676:
Metafont will always copy a string (does not make references).
 
<langsyntaxhighlight lang="metafont">string s, a;
s := "hello";
a := s;
Line 1,379 ⟶ 1,682:
message s; % writes "hello world"
message a; % writes "hello"
end</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">phrase = "hi"
copy = phrase
print phrase
print copy</langsyntaxhighlight>
 
=={{header|MIPS Assembly}}==
This does a full copy of the string, not just copying the pointer to the string's contents.
<langsyntaxhighlight lang="mips">.data
.text
Line 1,411 ⟶ 1,714:
addi $sp, $sp, 4
jr $ra
</syntaxhighlight>
</lang>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">src = "Hello"
new_alias = src
 
Line 1,422 ⟶ 1,725:
puts 'non-interned strings are not equal' if str_copy != src
puts 'compare strings with equals()' if str_copy.equals(src)
</syntaxhighlight>
</lang>
 
=={{header|Modula-3}}==
Strings in Modula-3 have the type <code>TEXT</code>.
<langsyntaxhighlight lang="modula3">VAR src: TEXT := "Foo";
VAR dst: TEXT := src;</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<syntaxhighlight lang="text">SET S1="Greetings, Planet"
SET S2=S1</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">a = "Hello"
b = a</langsyntaxhighlight>
 
=={{header|Neko}}==
<langsyntaxhighlight Nekolang="neko">var src = "Hello"
var dst = src</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle;
Line 1,460 ⟶ 1,763:
// I am not changed
}
}</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,473 ⟶ 1,776:
 
say s1
say s2</langsyntaxhighlight>
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,483 ⟶ 1,786:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(define (assert f msg) (if (not f) (println msg)))
 
(setq s "Greetings!" c (copy s))
Line 1,502 ⟶ 1,805:
true
 
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var
c = "This is a string"
d = c # Copy c into a new string</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">10 A$ = "HELLO"
20 B$ = A$
30 A$ = "HI"
40 PRINT A$, B$</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">MODULE CopyString;
TYPE
String = ARRAY 128 OF CHAR;
Line 1,525 ⟶ 1,828:
a := "plain string";
COPY(a,b);
END CopyString.</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">a := "GoodBye!";
b := a;</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 1,536 ⟶ 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.
 
<langsyntaxhighlight lang="objc">NSString *original = @"Literal String";
NSString *new = [original copy];
NSString *anotherNew = [NSString stringWithString:original];
NSString *newMutable = [original mutableCopy];</langsyntaxhighlight>
 
Mutable strings - you can get either new mutable (if you use <code>mutableCopy</code>) or immutable (if you use <code>copy</code>) string:
 
<langsyntaxhighlight lang="objc">NSMutableString *original = [NSMutableString stringWithString:@"Literal String"];
NSString *immutable = [original copy];
NSString *anotherImmutable = [NSString stringWithString:original];
NSMutableString *mutable = [original mutableCopy];</langsyntaxhighlight>
 
Copying a CString into an NSString:
 
<langsyntaxhighlight lang="objc">const char *cstring = "I'm a plain C string";
NSString *string = [NSString stringWithUTF8String:cstring];</langsyntaxhighlight>
 
Copying from data, possibly not null terminated:
 
<langsyntaxhighlight lang="objc">char bytes[] = "some data";
NSString *string = [[NSString alloc] initWithBytes:bytes length:9 encoding:NSASCIIStringEncoding];</langsyntaxhighlight>
 
And of course, if a C string is needed, you can use standard functions like strcpy.
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let src = "foobar"</langsyntaxhighlight>
<br/>
Before OCaml 4.02 (2014), strings were mutable and explicit deep copying was needed:
<langsyntaxhighlight lang="ocaml">let dst = String.copy src</langsyntaxhighlight>
<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.
<langsyntaxhighlight lang="ocaml">(* 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 *)</langsyntaxhighlight>
<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:
<langsyntaxhighlight lang="ocaml">let dst = src</langsyntaxhighlight>
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/>
Line 1,581 ⟶ 1,884:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">str2 = str1</langsyntaxhighlight>
 
=={{header|Oforth}}==
To make a copy of the reference, just dup the string
<langsyntaxhighlight Oforthlang="oforth">"abcde" dup</langsyntaxhighlight>
 
There is no need to copy a string content as strings are immutable. If really needed :
<langsyntaxhighlight Oforthlang="oforth">StringBuffer new "abcde" << </langsyntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(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))
</syntaxhighlight>
{{Out}}
<pre>
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
</pre>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx ***************************************************************
* 16.05.2013 Walter Pachl
**********************************************************************/
Line 1,608 ⟶ 1,941:
Say 's2='s2
i1=s1~identityhash; Say 's1~identityhash='i1
i2=s2~identityhash; Say 's2~identityhash='i2</langsyntaxhighlight>
{{out}}
<pre>s1=This is a Rexx string
Line 1,620 ⟶ 1,953:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
string s, t="hello"
s=t
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Assignment in GP always copies.
<langsyntaxhighlight lang="parigp">s1=s</langsyntaxhighlight>
 
In PARI, strings can be copied and references can be made.
<langsyntaxhighlight Clang="c">GEN string_copy = gcopy(string);
GEN string_ref = string;</langsyntaxhighlight>
 
=={{header|Pascal}}==
''See also: [[#Delphi|Delphi]]''
 
<langsyntaxhighlight lang="pascal" highlight="9,13,15">program in,outcopyAString;
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}}==
Line 1,668 ⟶ 1,989:
To copy a string, just use ordinary assignment:
 
<langsyntaxhighlight lang="perl">my $original = 'Hello.';
my $new = $original;
$new = 'Goodbye.';
print "$original\n"; # prints "Hello."</langsyntaxhighlight>
 
To create a reference to an existing string, so that modifying the referent changes the original string, use a backslash:
 
<langsyntaxhighlight lang="perl">my $original = 'Hello.';
my $ref = \$original;
$$ref = 'Goodbye.';
print "$original\n"; # prints "Goodbye."</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="perl">my $original = 'Hello.';
our $alias;
local *alias = \$original;
$alias = 'Good evening.';
print "$original\n"; # prints "Good evening."</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="perl">use Lexical::Alias;
my $original = 'Hello.';
my $alias;
alias $alias, $original;
$alias = 'Good evening.';
print "$original\n"; # prints "Good evening."</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Use of strings is utterly intuitive with no unexpected side effects. For example
<!--<langsyntaxhighlight Phixlang="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;">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,707 ⟶ 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: #0000FF;">?<span style="color: #0000FF;">{<span style="color: #000000;">one<span style="color: #0000FF;">,<span style="color: #000000;">two<span style="color: #0000FF;">}
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,716 ⟶ 2,037:
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php">$src = "Hello";
$dst = $src;</langsyntaxhighlight>
 
=={{header|Picat}}==
Use <code>copy_term/1</code> to ensure that the original string is not changed.
<syntaxhighlight lang="picat">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.</syntaxhighlight>
 
{{out}}
<pre>s1 = string
s1 = xtring
s2 = xtring
 
s3 = string
s4 = xtring</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq Str1 "abcdef")
(setq Str2 Str1) # Create a reference to that symbol
(setq Str3 (name Str1)) # Create new symbol with name "abcdef"</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">int main(){
string hi = "Hello World.";
string ih = hi;
}</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> declare (s1, s2) character (20) varying;
s1 = 'now is the time';
s2 = s1;</langsyntaxhighlight>
 
=={{header|Pop11}}==
Line 1,739 ⟶ 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:
 
<langsyntaxhighlight lang="pop11">vars src, dst;
'Hello' -> src;
copy(src) -> dst;</langsyntaxhighlight>
 
One can also combine assignment (initialization) with variable declarations:
 
<langsyntaxhighlight lang="pop11">vars src='Hello';
vars dst=copy(src);</langsyntaxhighlight>
 
=={{header|PostScript}}==
In PostScript,
<langsyntaxhighlight lang="postscript">(hello) dup length string copy</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="powershell">$str = "foo"
$dup = $str</langsyntaxhighlight>
To actually create a copy the <code>Clone()</code> method can be used:
<langsyntaxhighlight lang="powershell">$dup = $str.Clone()</langsyntaxhighlight>
 
=={{header|ProDOS}}==
<langsyntaxhighlight ProDOSlang="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- </langsyntaxhighlight>
 
=={{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.
You cannot reassign a value once it has been unified, it is not logical to have a value equal more than one thing.
<langsyntaxhighlight lang="prolog">?- A = "A test string", A = B.
A = B, B = "A test string".</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">src$ = "Hello"
dst$ = src$</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,779 ⟶ 2,128:
Since strings are immutable, all copy operations return the same string, with the reference count increased as appropriate
 
<langsyntaxhighlight lang="python">>>> src = "hello"
>>> a = src
>>> b = src[:]
Line 1,786 ⟶ 2,135:
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True</langsyntaxhighlight>
 
To actually copy a string:
 
<langsyntaxhighlight lang="python">>>> a = 'hello'
>>> b = ''.join(a)
>>> a == b
True
>>> b is a ### Might be True ... depends on "interning" implementation details!
False</langsyntaxhighlight>
 
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 1,806 ⟶ 2,155:
<br>
Strings are immutable.
<langsyntaxhighlight Quackerylang="quackery">$ "hello" dup</langsyntaxhighlight>
 
=={{header|R}}==
Copy a string by value:
<langsyntaxhighlight Rlang="r">str1 <- "abc"
str2 <- str1</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,829 ⟶ 2,178:
(string-fill! s3 #\!)
(printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,835 ⟶ 2,184:
 
There is no special handling needed to copy a string; just assign it to a new variable:
<syntaxhighlight lang="raku" perl6line>my $original = 'Hello.';
my $copy = $original;
say $copy; # prints "Hello."
$copy = 'Goodbye.';
say $copy; # prints "Goodbye."
say $original; # prints "Hello."</langsyntaxhighlight>
 
You can also bind a new variable to an existing one so that each refers to, and can modify the same string.
<syntaxhighlight lang="raku" perl6line>my $original = 'Hello.';
my $bound := $original;
say $bound; # prints "Hello."
$bound = 'Goodbye.';
say $bound; # prints "Goodbye."
say $original; # prints "Goodbye."</langsyntaxhighlight>
 
<!-- 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.
<syntaxhighlight lang="raku" perl6line># y $original = 'Hello.';
#my $bound-ro ::= $original;
#say $bound-ro; # prints "Hello."
Line 1,863 ⟶ 2,212:
say $bound-ro; # prints "Hello."
$original = 'Goodbye.';
say $bound-ro; # prints "Goodbye."</langsyntaxhighlight>
-->
 
Line 1,870 ⟶ 2,219:
Copy a string by reference:
 
<langsyntaxhighlight lang="raven">'abc' as a
a as b</langsyntaxhighlight>
 
Copy a string by value:
 
<langsyntaxhighlight lang="raven">'abc' as a
a copy as b</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "String Copy"
URL: http://rosettacode.org/wiki/Copy_a_string
Line 1,899 ⟶ 2,248:
 
y: copy/part skip x 2 3
print ["Partial copy from offset:" mold x "," mold y]</langsyntaxhighlight>
 
{{out}}
Line 1,910 ⟶ 2,259:
 
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
Red[]
originalString: "hello wordl"
Line 1,916 ⟶ 2,265:
; OR
copiedString2: copy originalString
</syntaxhighlight>
</lang>
 
=={{header|Retro}}==
<syntaxhighlight lang Retro="retro">'this_is_a_string dup s:temp</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,930 ⟶ 2,279:
Also note that &nbsp; ''all'' &nbsp; REXX values (variables) are
stored as (varying length) &nbsp; ''character strings''.
<langsyntaxhighlight lang="rexx">src = "this is a string"
dst = src</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
cStr1 = "Hello!" # create original string
cStr2 = cStr1 # make new string from original
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
<langsyntaxhighlight RLaBlang="rlab">>> s1 = "A string"
A string
>> s2 = s1
A string</langsyntaxhighlight>
 
=={{header|Robotic}}==
<langsyntaxhighlight lang="robotic">
set "$string1" to "This is a string"
set "$string2" to "$string1"
* "&$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}}==
In Ruby, String are mutable.
<langsyntaxhighlight lang="ruby">original = "hello"
reference = original # copies reference
copy1 = original.dup # instance of original.class
Line 1,962 ⟶ 2,317:
p reference #=> "hello world!"
p copy1 #=> "hello"
p copy2 #=> "hello"</langsyntaxhighlight>
 
There is a method of Object#clone, too, in the copy of the object.
<langsyntaxhighlight lang="ruby">original = "hello".freeze # prevents further modifications
copy1 = original.dup # copies contents (without status)
copy2 = original.clone # copies contents (with status)
Line 1,971 ⟶ 2,326:
p copy1 << " world!" #=> "hello world!"
p copy2.frozen? #=> true
p copy2 << " world!" #=> can't modify frozen String (RuntimeError)</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">origString$ = "Hello!" ' create original string
newString$ = origString$ ' make new strig from original</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let s1 = "A String";
let mut s2 = s1;
Line 1,985 ⟶ 2,340:
 
println!("s1 = {}, s2 = {}", s1, s2);
}</langsyntaxhighlight>
 
Output: <syntaxhighlight lang="text">s1 = A String, s2 = Another String</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
s ::= "a string";
Line 1,996 ⟶ 2,351:
-- s1 is a copy
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala"> val src = "Hello"
// Its actually not a copy but a reference
// That is not a problem because String is immutable
Line 2,011 ⟶ 2,366:
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.</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define dst (string-copy src))</langsyntaxhighlight>
 
=={{header|Seed7sed}}==
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";</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">(* In SenseTalk, assignments normally always make copies of values. *)
 
put "glorious" into myWord
Line 2,040 ⟶ 2,397:
put "myRef: " & myRef
put "another: " & another
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,050 ⟶ 2,407:
 
=={{header|Shiny}}==
<langsyntaxhighlight lang="shiny">src: 'hello'
cpy: src</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">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+''; # ==//==</langsyntaxhighlight>
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
TEXT ORIGINAL, REFERENCE, COPY1;
 
Line 2,087 ⟶ 2,444:
OUTTEXT(COPY1);
OUTIMAGE;
END;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,098 ⟶ 2,455:
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">[ | :s | s == s copy] applyTo: {'hello'}. "returns False"</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang="smalltalk">|s1 s2|
"bind the var s1 to the object string on the right"
s1 := 'i am a string'.
Line 2,108 ⟶ 2,465:
s2 := s1.
"bind s2 to a copy of the object bound to s1"
s2 := (s1 copy).</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol4">
* copy a to b
b = a = "test"
Line 2,119 ⟶ 2,476:
b "t" = "T"
output = b
end</langsyntaxhighlight>
 
{{out}}
Line 2,132 ⟶ 2,489:
 
Instead, maybe you want to create a <code>CharArray.array</code> (mutable string) from an existing <code>string</code>:
<langsyntaxhighlight lang="sml">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 *)</langsyntaxhighlight>
 
or from another <code>CharArray.array</code>:
<langsyntaxhighlight lang="sml">val srcCopy2 = CharArray.array (CharArray.length srcCopy, #"x"); (* 'x' is just dummy character *)
CharArray.copy {src = srcCopy, dst = srcCopy2, di = 0};</langsyntaxhighlight>
 
=={{header|Swift}}==
Just use assignment:
<langsyntaxhighlight lang="swift">var src = "Hello"
var dst = src</langsyntaxhighlight>
Strings in Swift are value types, so assigning copies the string.
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set src "Rosetta Code"
set dst $src</langsyntaxhighlight>
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.
Line 2,155 ⟶ 2,512:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">:"Rosetta Code"→Str1
:Str1→Str2</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
<langsyntaxhighlight lang="ti89b">:"Rosetta Code"→str1
:str1→str2</langsyntaxhighlight>
 
=={{header|Toka}}==
<langsyntaxhighlight lang="toka">" hello" is-data a
a string.clone is-data b</langsyntaxhighlight>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#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)
)
)
}</syntaxhighlight>{{out}}
<pre>
Good bye!
Hello!
Good bye!
</pre>
 
=={{header|Trith}}==
Strings are immutable character sequences,
so copying a string just means duplicating the reference at the top of the stack:
<langsyntaxhighlight lang="trith">"Hello" dup</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
str="Hello"
dst=str</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="bash">foo="Hello"
bar=$foo # This is a copy of the string</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl string a b
set a "hello"
set b a</langsyntaxhighlight>
 
=={{header|V}}==
Line 2,190 ⟶ 2,568:
so the string is immutable.
 
<langsyntaxhighlight lang="v">"hello" dup</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="vb">Sub copystring()
a = "Hello World!"
b = a
Line 2,200 ⟶ 2,578:
Debug.Print b
Debug.Print a
End Sub</langsyntaxhighlight>{{out}}
<pre>Hello World!
I'm gone</pre>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">let str1 = "original string"
let str2 = str1
let str1 = "new string"
 
echo "String 1:" str1
echo "String 2:" str2</langsyntaxhighlight>
 
{{Out}}
Line 2,220 ⟶ 2,598:
 
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">'Immutable Strings
Dim a = "Test string"
Dim b = a 'reference to same string
Line 2,228 ⟶ 2,606:
Dim x As New Text.StringBuilder("Test string")
Dim y = x 'reference
Dim z = New Text.StringBuilder(x.ToString) 'new string</langsyntaxhighlight>
 
Alternatively, you can use, with all versions of the .NET framework:
<langsyntaxhighlight lang="vbnet">Dim a As String = "Test String"
Dim b As String = String.Copy(a) ' New string</langsyntaxhighlight>
 
=={{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}}==
Line 2,238 ⟶ 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.
<langsyntaxhighlight ecmascriptlang="wren">var s = "wren"
var t = s
System.print("Are 's' and 't' equal? %(s == t)")</langsyntaxhighlight>
 
{{out}}
Line 2,250 ⟶ 2,641:
{{works with|nasm}}
creating a second 0 terminated string with the same content:
<langsyntaxhighlight lang="asm">
section .data
string db "Hello World", 0
Line 2,271 ⟶ 2,662:
xor eax, eax
ret
</syntaxhighlight>
</lang>
 
creating a second string; first byte signals length of string
<langsyntaxhighlight lang="asm">
section .data
string db 11,"Hello World"
Line 2,297 ⟶ 2,688:
xor eax, eax
ret
</syntaxhighlight>
</lang>
 
=={{header|X86-64 Assembly}}==
===UASM 2.5452===
<langsyntaxhighlight lang="asm">
option casemap:none
option literals:on
Line 2,325 ⟶ 2,716:
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)
Line 2,333 ⟶ 2,724:
mov dp, rax ;; Copy it from RAX to dp
mov rbx,rdi ;; Make a ;;preservecopy registersof RDI, cause over writes due to ABI callscall 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
Line 2,344 ⟶ 2,735:
 
end
</syntaxhighlight>
</lang>
{{out}}
Output
<pre>
-> s (0x40303f) = Goodbye, World!
Line 2,351 ⟶ 2,742:
-> dp (0x4030a4) = Goodbye, World!
-> 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>
 
Line 2,359 ⟶ 2,872:
The string copy routine from the standard library is shown.
 
<langsyntaxhighlight XPL0lang="xpl0">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
Line 2,371 ⟶ 2,884:
S2:= S1; \S2 now also points to the string
StrCopy(S1, S3); \S3 points to a separate copy of the string
]</langsyntaxhighlight>
 
=={{header|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.
 
<syntaxhighlight lang="z80">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.</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:
<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 a,>MyString ; > represents the high byte of the address. Some assemblers use HIGH() with the label in the parentheses.
ld (PointerVariable+1),a</syntaxhighlight>
 
===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:
 
<syntaxhighlight lang="z80">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</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}}==
<langsyntaxhighlight lang="zig">const std = @import("std");
 
const debug = std.debug;
Line 2,395 ⟶ 2,960:
debug.assert(mem.eql(u8, dest1[0..], "A string."));
debug.assert(mem.eql(u8, dest2[0..], "A string."));
}</langsyntaxhighlight>
 
=={{header|zkl}}==
Strings are immutable so copy is just return the string:
<langsyntaxhighlight lang="zkl">"abc".copy() // noop</langsyntaxhighlight>
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module Main;
var
Line 2,414 ⟶ 2,979:
copy(c,r);writeln(r);
end Main.
</syntaxhighlight>
</lang>
 
=={{header|Zoomscript}}==
For typing:
<syntaxhighlight lang="zoomscript">var a
<lang Zoomscript>var a
var b
a = "World"
b = a
a = "Hello"
print (a," ",b)</langsyntaxhighlight>
For importing:
 
Line 2,430 ⟶ 2,995:
=={{header|ZX Spectrum Basic}}==
 
<langsyntaxhighlight lang="basic">10 LET a$ = "Hello": REM a$ is the original string
20 LET b$ = a$: REM b$ is the copy</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
Version 1:
Assign variable "s" to variable "b".
<syntaxhighlight lang="hopper">
#include <hopper.h>
main:
s = "string to copy"
t = s
{s,"\n",t}println
exit(0)
</syntaxhighlight>
Output:
string to copy
string to copy
 
Version 2:
Soft copy to variable (CPY).
<syntaxhighlight lang="hopper">
#include <hopper.h>
main:
s=""
{"1:","string to copy"},cpy(s),println
{"2:",s}println
exit(0)
</syntaxhighlight>
Output:
1:string to copy
2:string to copy
 
Version 3:
From stack to var: hard copy (move, MOV).
<syntaxhighlight lang="hopper">
#include <hopper.h>
main:
s=""
{"string to copy"},mov(s)
{s}println
exit(0)
</syntaxhighlight>
Output:
string to copy
Anonymous user