Copy a string

From Rosetta Code
Revision as of 14:17, 23 July 2013 by rosettacode>Edward H (Added COBOL example.)
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. Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string.

ABAP

<lang ABAP>data: lv_string1 type string value 'Test',

     lv_string2 type string.

lv_string2 = lv_string1.</lang>

ActionScript

Strings are immutable in ActionScript, and can safely be assigned with the assignment operator, much as they can in Java.[1] <lang ActionScript>var str1:String = "Hello"; var str2:String = str1;</lang>

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.

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

Bounded Length String Copying

<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;</lang> Ada Bounded_String type provides a number of functions for dealing with slices.

Unbounded Length String Copying

<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;</lang>

Aime

The intrinsic text type is immediate, immutable and cannot be referred more than once. Copying an intrinsic string: <lang aime>text s, t; t = "Rosetta"; s = t;</lang> Data of the non intrinsic byte array type can be referred more than once. Copying a binary array of bytes: <lang aime>data s, t;

  1. Copy -t- into -s-

b_copy(s, t);

  1. Set -s- as a reference of the object -t- is pointing

b_set(s, t);

  1. or:

s = t; </lang>

ALGOL 68

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

<lang algol68>(

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

)</lang>

AutoHotkey

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

AutoIt

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

AWK

<lang awk>BEGIN {

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

}</lang>

BASIC

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

Batch File

Since the only variables are environment variables, creating a string copy is fairly straightforward: <lang dos>set src=Hello set dst=%src%</lang>

BBC BASIC

<lang bbcbasic> 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$</lang>

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: <lang bracmat>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 } </lang>

C

<lang c>#include <stdlib.h> /* exit(), free() */

  1. include <stdio.h> /* fputs(), perror(), printf() */
  2. 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; }</lang>

Library: BSD libc

<lang c>#include <stdlib.h> /* exit() */

  1. include <stdio.h> /* fputs(), printf() */
  2. 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; }</lang>

C++

<lang>#include <iostream>

  1. include <string>
  2. include <algorithm>

int main( ) {

  std::string original ( "This is the original" ) ;
  std::string mycopy( original.length( ) , ' ' ) ;
  std::copy ( original.begin( ) , original.end( ) , mycopy.begin( ) ) ;
  std::cout << "This is the copy: " << mycopy << std::endl ;
  original.assign( "Now we change the original! " ) ;
  std::cout << "mycopy still is " << mycopy << std::endl ;
  return 0 ;

}</lang>

C#

<lang csharp>string src = "Hello"; string dst = src;</lang>

Clojure

<lang clojure>(let [s "hello"

     s1 s]
 (println s s1))</lang>

COBOL

Translation of: C#

<lang cobol>MOVE "Hello" TO src MOVE src TO dst</lang>

ColdFusion

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

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

Common Lisp

<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
 (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!!!!!"</lang>

D

<lang 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;

}</lang>

Delphi

Delphi strings are reference counted with copy on write semantics.

<lang Delphi>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.</lang>


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.

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.

Erlang

<lang erlang>Src = "Hello". Dst = Src.</lang>


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.

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

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: <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</lang>

Factor

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

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

   "New string"</lang>

Factor string buffers (sbufs) are mutable and growable.

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

   SBUF" Grow me!  OK."</lang>

Convert a string buffer to a string.

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

   "I'll be a string someday."</lang>

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:

<lang forth>\ 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</lang>

Fortran

<lang fortran>str2 = str1</lang>

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.

Gambas

Note that the DIM statement is optional in Gambas.

<lang gambas>DIM src AS String DIM dst AS String src = "Hello" dst = src</lang>

GAP

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

  1. "less"
  1. Here is a true copy

a := "more"; b := ShallowCopy(a); b{[1..4]} := "less"; a;

  1. "more"</lang>

GML

<lang GML>src = "string" dest = src</lang>

Go

Just use assignment: <lang go>src := "Hello" dst := src</lang> 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.

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: <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</lang>

Test Program: <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 !=)</lang>

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

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

Haskell

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

HicEst

<lang hicest>src = "Hello World" dst = src</lang>

Icon and Unicon

Strings in Icon are immutable. <lang icon>procedure main()

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

end</lang>

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

<lang j>src =: 'hello' dest =: src</lang>

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. <lang java>String src = "Hello"; String newAlias = src; String strCopy = new String(src);

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

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

JavaScript

Objects can be copied in JavaScript via simple reassignment. Changes to the properties of one will be reflected in the other: <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"</lang>

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 <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"</lang>

Joy

<lang joy>"hello" dup</lang>

Strings are immutable.

KonsolScript

<lang KonsolScript>Var:String str1 = "Hello"; Var:String str2 = str1;</lang>

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.

Lang5

<lang lang5>'hello dup</lang>

LFE

<lang lisp>(let* ((a '"data assigned to a")

      (b a)) 
 (: io format '"Contents of 'b': ~s~n" (list b)))</lang>

Output:

Contents of 'b': data assigned to a

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

<lang lisp>> (set a '"data") "data" > a "data" > (set b a) "data" > b "data"</lang>

Liberty BASIC

<lang lb>src$ = "Hello" dest$ = src$ print src$ print dest$

</lang>

Lisaac

<lang Lisaac>+ scon : STRING_CONSTANT; + svar : STRING;

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

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

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 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</lang>

Lua

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

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. <lang Maple> > 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 </lang>

Mathematica

<lang Mathematica>a="Hello World" b=a</lang>

MATLAB

<lang MATLAB>string1 = 'Hello'; string2 = string1;</lang>

Maxima

<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, 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"</lang>


MAXScript

<lang maxscript>str1 = "Hello" str2 = copy str1</lang>

Metafont

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

<lang metafont>string s, a; s := "hello"; a := s; s := s & " world"; message s;  % writes "hello world" message a;  % writes "hello" end</lang>

Mirah

<lang 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) </lang>

Modula-3

Strings in Modula-3 have the type TEXT. <lang modula3>VAR src: TEXT := "Foo"; VAR dst: TEXT := src;</lang>

MUMPS

<lang>SET S1="Greetings, Planet" SET S2=S1</lang>

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. <lang Nemerle>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
   }

}</lang>

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: <lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols nobinary

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

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

say s1 say s2</lang> 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

<lang 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.")</lang>

Oberon-2

<lang oberon2>MODULE CopyString; TYPE String = ARRAY 128 OF CHAR; VAR a,b: String;

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

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.

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

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

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

Copying a CString into an NSString:

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

Copying from data, possibly not null terminated:

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

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

Objeck

<lang objeck>a := "GoodBye!"; b := a;</lang>

OCaml

<lang ocaml>let dst = String.copy src</lang>

Octave

<lang octave>str2 = str1</lang>

OxygenBasic

<lang oxygenbasic> string s, t="hello" s=t </lang>

ooRexx

<lang 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</lang> Output:

s1=This is a Rexx string
s2=This is a Rexx string
s1~identityhash=264720683
s2~identityhash=264720683
s1=This is a Rexx string
s2=This_is_a_Rexx_string
s1~identityhash=264720683
s2~identityhash=264721639

PARI/GP

Assignment in GP always copies. <lang parigp>s1=s</lang>

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

Pascal

<lang pascal>program in,out;

type

  pString = ^string;

var

  s1,s2 : string ;
  pStr  : pString ;

begin

  /* direct copy */
  s1 := 'Now is the time for all good men to come to the aid of their party.'
  s2 := s1 ;
  writeln(s1);
  writeln(s2);
  /* By Reference */
  pStr := @s1 ;
  writeln(pStr^);
  pStr := @s2 ;
  writeln(pStr^);

end;</lang>

Perl

To copy a string, just use ordinary assignment:

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

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.'; my $ref = \$original; $$ref = 'Goodbye.'; print "$original\n"; # prints "Goodbye."</lang>

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.'; our $alias; local *alias = \$original; $alias = 'Good evening.'; print "$original\n"; # prints "Good evening."</lang>

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: <lang perl>use Lexical::Alias; my $original = 'Hello.'; my $alias; alias $alias, $original; $alias = 'Good evening.'; print "$original\n"; # prints "Good evening."</lang>


Perl 6

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

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.'; my $bound := $original; say $bound; # prints "Hello." $bound = 'Goodbye.'; say $bound; # prints "Goodbye." say $original; # prints "Goodbye."</lang>

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>my $original = 'Hello.'; my $bound-ro ::= $original; say $bound-ro; # prints "Hello." try {

 $bound-ro = 'Runtime error!';
 CATCH {
   say "$!";         # prints "Cannot modify readonly value"
 };

}; say $bound-ro; # prints "Hello." $original = 'Goodbye.'; say $bound-ro; # prints "Goodbye."</lang>

PHP

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

PicoLisp

<lang PicoLisp>(setq Str1 "abcdef") (setq Str2 Str1) # Create a reference to that symbol (setq Str3 (name Str1)) # Create new symbol with name "abcdef"</lang>

Pike

<lang pike>int main(){

  string hi = "Hello World.";
  string ih = hi;

}</lang>

PL/I

<lang pli> declare (s1, s2) character (20) varying;

  s1 = 'now is the time';
  s2 = s1;</lang>

Pop11

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; 'Hello' -> src; copy(src) -> dst;</lang>

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

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

PostScript

In PostScript, <lang postscript>(hello) dup length string copy</lang>

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: <lang powershell>$str = "foo" $dup = $str</lang> To actually create a copy the Clone() method can be used: <lang powershell>$dup = $str.Clone()</lang>

PureBasic

<lang PureBasic>src$ = "Hello" dst$ = src$</lang>

ProDOS

<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=c /userinput=1 /title=Enter file to copy to: copy -a- from -b- to -c- </lang>

Python

Works with: Python version 2.3, 2.4, and 2.5

Since strings are immutable, all copy operations return the same string. Probably the reference is increased.

<lang python>>>> 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</lang>

To actually copy a string:

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

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.

R

Copy a string by value: <lang R>str1 <- "abc" str2 <- str1</lang>

Racket

<lang Racket>

  1. 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!!!!!!"

</lang>

Raven

Copy a string by reference:

<lang raven>'abc' as a a as b</lang>

Copy a string by value:

<lang raven>'abc' as a a copy as b</lang>

REBOL

<lang REBOL>REBOL [

   Title: "String Copy"
   Date: 2009-12-16
   Author: oofoe
   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]</lang>

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"

Retro

<lang Retro>"this is a string" dup tempString</lang>

REXX

<lang rexx>src = "this is a string" dst = src</lang>

RLaB

<lang RLaB>>> s1 = "A string" A string >> s2 = s1 A string</lang>

Ruby

<lang ruby>original = "hello" reference = original copy1 = original.dup # instance of original.class copy2 = String.new(original) # instance of String</lang>


Run BASIC

<lang runbasic>origString$ = "Hello!" ' create original string newString$ = origString$ ' make new strig from original</lang>

Sather

<lang sather>class MAIN is

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

end;</lang>

Scala

<lang scala>val src = "Hello" val des = src</lang>

Scheme

<lang scheme>(define dst (string-copy src))</lang>

Seed7

<lang seed7>var string: dest is "";

dest := "Hello";</lang>

Shiny

<lang shiny>src: 'hello' cpy: src</lang>

Slate

<lang slate>[ | :s | s == s copy] applyTo: {'hello'}. "returns False"</lang>


Smalltalk

<lang 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).</lang>

SNOBOL4

<lang snobol4>

  • copy a to b
         b = a = "test"
         output = a
         output = b
  • change the copy
         b "t" = "T"
         output = b

end</lang>

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: <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 *)</lang>

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

Tcl

<lang tcl>set src "Rosetta Code" set dst $src</lang> 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

<lang ti83b>:"Rosetta Code"→Str1

Str1→Str2</lang>

TI-89 BASIC

<lang ti89b>:"Rosetta Code"→str1

str1→str2</lang>

Toka

<lang toka>" hello" is-data a a string.clone is-data b</lang>

Trith

Strings are immutable character sequences, so copying a string just means duplicating the reference at the top of the stack: <lang trith>"Hello" dup</lang>

TUSCRIPT

<lang tuscript>$$ MODE TUSCRIPT str="Hello" dst=str</lang>

UNIX Shell

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

V

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

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

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vbnet>'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</lang>

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

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.

<lang 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 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 ]</lang>

ZX Spectrum Basic

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