String append
You are encouraged to solve this task according to the task description, using any language you may know.
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
- Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
ALGOL 68
File: String_append.a68<lang algol68>#!/usr/bin/a68g --script #
- -*- coding: utf-8 -*- #
STRING str := "12345678"; str +:= "9!"; print(str)</lang>
- Output:
123456789!
AutoHotkey
<lang autohotkey>s := "Hello, " s .= "world." MsgBox % s</lang>
- Output:
Hello, world.
AWK
<lang AWK>
- syntax: GAWK -f STRING_APPEND.AWK
BEGIN {
s = "foo" s = s "bar" print(s) exit(0)
} </lang>
- Output:
foobar
Axe
<lang axe>Lbl STRCAT Copy(r₂,r₁+length(r₁),length(r₂)+1) r₁ Return</lang>
BASIC
Applesoft BASIC
<lang BASIC>S$ = "Hello" S$ = S$ + " World!" PRINT S$</lang>
BBC BASIC
<lang BBC BASIC> S$="Hello"
S$+=" World!" PRINT S$ END</lang>
- Output:
Hello World!
Bracmat
<lang Bracmat>str="Hello"; str$(!str " World!"):?str; out$!str;</lang>
- Output:
Hello World!
C
<lang c>#include<stdio.h>
- include<string.h>
int main() {
char str[24]="Good Morning"; char *cstr=" to all"; char *cstr2=" !!!"; int x=0; //failure when space allocated to str is insufficient.
if(sizeof(str)>strlen(str)+strlen(cstr)+strlen(cstr2)) { /* 1st method*/ strcat(str,cstr);
/*2nd method*/ x=strlen(str); sprintf(&str[x],"%s",cstr2);
printf("%s\n",str);
} return 0;
}</lang>
- Output:
Good Morning to all !!!
C++
<lang cpp>#include <iostream>
- include <string>
int main( ) {
std::string greeting( "Hello" ) ; greeting.append( " , world!" ) ; std::cout << greeting << std::endl ; return 0 ;
}</lang>
- Output:
Hello , world!
C#
<lang csharp>class Program {
static void Main(string[] args) { string x = "foo"; x += "bar"; System.Console.WriteLine(x); }
}</lang>
Clojure
Using global vars. <lang clojure>user=> (def s "app")
- 'user/s
user=> s "app" user=> (def s (str s "end"))
- 'user/s
user=> s "append"</lang>
Using local bindings. <lang clojure> user=> (let [s "ap", s (str s "pend")] s) "append"</lang>
COBOL
COBOL is not really a variable length field programming language. Most data items are fixed in size at compile time.
This example uses OCCURS DEPENDING ON, and reference modification to simulate a string append, all within an already maximally bounded character field. This type of programming task, while possible, is not overly common in COBOL applications.
<lang COBOL> identification division.
program-id. string-append.
data division. working-storage section. 01 some-string. 05 elements pic x occurs 0 to 80 times depending on limiter. 01 limiter usage index value 7. 01 current usage index.
procedure division. append-main.
move "Hello, " to some-string
*> extend the limit and move using reference modification set current to length of some-string set limiter up by 5 move "world" to some-string(current + 1:) display some-string
goback. end program string-append.
</lang>
- Output:
$ cobc -xj string-append.cob Hello, world
CoffeeScript
<lang coffeescript>a = "Hello, " b = "World!" c = a + b
console.log c</lang> Or with concat: <lang coffeescript>console.log "Hello, ".concat "World!"</lang>
- Output:
Hello, World!
Common Lisp
Similar to the Racket solution, a macro is necessary to append in-place: <lang lisp>(defmacro concatenatef (s &rest strs)
"Append additional strings to the first string in-place." `(setf ,s (concatenate 'string ,s ,@strs)))
(defvar *str* "foo") (concatenatef *str* "bar") (format T "~a~%" *str*) (concatenatef *str* "baz" "abc" "def") (format T "~a~%" *str*)</lang>
Output:
foobar foobarbazabcdef
D
<lang d>import std.stdio;
void main() {
string s = "Hello"; s ~= " world!"; writeln(s);
}</lang>
- Output:
Hello world!
EchoLisp
<lang lisp>
- Solution from Common Lisp and Racket
(define-syntax-rule (set-append! str tail)
(set! str (string-append str tail)))
(define name "Albert") → name
(set-append! name " de Jeumont-Schneidre") name
→ "Albert de Jeumont-Schneidre"
</lang>
Elena
<lang elena>#import system.
- symbol program =
[
#var s := String new:"Hello". s += " World". console writeLine:s.
].</lang>
Elixir
<lang elixir>iex(60)> s = "Hello" "Hello" iex(61)> s <> " World!" "Hello World!"</lang>
Emacs Lisp
version 1
<lang Emacs Lisp> (defun glue (str1 str2)
(concat str1 str2) )
</lang>
version 2
<lang Emacs Lisp> (defun glue (str1 str2)
(format "%s%s" str1 str2) )
</lang> Eval: <lang Emacs Lisp> (setq str "Hello, ") (setq str (glue str "World!") ) (insert str) </lang> Output:
Hello, World!
Erlang
- Output:
1> S = "Hello". "Hello" 2> S ++ " world". "Hello world"
Euphoria
<lang euphoria> sequence string = "String"
printf(1,"%s\n",{string})
string &= " is now longer\n"
printf(1,"%s",{string}) </lang>
- Output:
String String is now longer
F#
Strings are immutable in .NET. To append (to the same variable) the variable has to be declared mutable. <lang fsharp>let mutable x = "foo" x <- x + "bar" printfn "%s" x</lang>
Forth
<lang Forth>Strings in Forth are simply named memory locations
create astring 256 allot \ create a "string"
s" Hello " astring PLACE \ initialize the string
s" World!" astring +PLACE \ append with "+place"
</lang>
Test at the console
<lang> ok s" Hello " astring place ok s" World!" astring +place ok astring count type Hello World! ok </lang>
Fortran
Using deferred length character strings:
<lang Fortran> program main
character(len=:),allocatable :: str
str = 'hello' str = str//' world'
write(*,*) str
end program main </lang>
Go
<lang go>s := "foo" s += "bar"</lang>
Icon and Unicon
In both languages you can:
<lang unicon> procedure main()
s := "foo" s ||:= "bar" write(s)
end </lang>
Outputs:
->ss foobar ->
Haskell
<lang haskell> main = putStrLn ("Hello" ++ "World") </lang>
J
<lang j> s=: 'new'
s
new
s=: s,' value' NB. append is in-place s
new value</lang>
Java
<lang Java>String sa = "Hello"; sa += ", World!"; System.out.println(sa);
StringBuilder ba = new StringBuilder(); ba.append("Hello"); ba.append(", World!"); System.out.println(ba.toString());</lang>
- Output:
Hello, World! Hello, World!
JavaScript
<lang JavaScript>var s1 = "Hello"; s1 += ", World!"; print(s1);
var s2 = "Goodbye"; // concat() returns the strings together, but doesn't edit existing string // concat can also have multiple parameters print(s2.concat(", World!"));</lang>
- Output:
"Hello, World!" "Goodbye, World!"
jq
jq's +
operator can be used to append two strings, and under certain circumstances the +=
operator can be used as an abbreviation for appending a string to an existing string. For example, all three of the following produce the same output:<lang jq>"Hello" | . += ", world!"
["Hello"] | .[0] += ", world!" | .[0]
{ "greeting": "Hello"} | .greeting += ", world!" | .greeting</lang>
However the +=
operator cannot be used with jq variables in the conventional manner. One could nevertheless use the technique illustrated by the following:<lang jq>"Hello" as $a | $a | . += ", world!" as $a | $a</lang>
Julia
<lang julia>s = "Hello" s *= ", world!"</lang>
- Output:
"Hello, world!"
Lasso
<lang Lasso>local(x = 'Hello')
- x->append(', World!')
- x</lang>
- Output:
Hello, World!
Lingo
<lang lingo>str = "Hello" put " world!" after str put str -- "Hello world!"</lang>
LiveCode
Livecode has an "after" keyword for this <lang LiveCode>local str="live" put "code" after str</lang> Output is "livecode"
Lua
Not possible as strings are immutable. We can demonstrate their immutability using 'self': <lang Lua>function string:show ()
print(self)
end
function string:append (s)
self = self .. s
end
x = "Hi " x:show() x:append("there!") x:show()</lang>
- Output:
Hi Hi
You can of course concatentate them and store the result in the original variable name but that requires a double reference: <lang Lua>x = "Hi " x = x .. "there!" print(x)</lang>
- Output:
Hi there!
Maple
<lang maple>a := "Hello"; b := cat(a, " World"); c := `||`(a, " World");</lang>
- Output:
"Hello" "Hello World" "Hello World"
Mathematica
<lang Mathematica> (* mutable strings are not supported *) s1 = "testing"; s1 = s1 <> " 123"; s1</lang>
- Output:
"testing 123"
NetRexx
<lang NetRexx>s_ = 'Hello' s_ = s_', world!' say s_</lang>
- Output:
Hello, world!
NewLISP
<lang NewLISP>(setq str "foo")
(push "bar" str -1)
- or as an alternative introduced in v.10.1
(extend str "bar")
(println str) </lang>
Nim
<lang nim>var str = "123456" str.add("78") # two ways str &= "9!" # to append</lang>
Objeck
<lang objeck> class Append {
function : Main(args : String[]) ~ Nil { x := "foo"; x->Append("bar"); x->PrintLine(); }
} </lang>
OCaml
<lang ocaml>let () =
let s = Buffer.create 17 in Buffer.add_string s "Bonjour"; Buffer.add_string s " tout le monde!"; print_endline (Buffer.contents s)</lang>
- Output:
Bonjour tout le monde!
Oforth
<lang Oforth>StringBuffer new "Hello, " << "World!" << println</lang>
PARI/GP
Not supported in GP. <lang parigp>s = "Hello"; s = Str(s, ", world!")</lang>
- Output:
%1 = "Hello, world!"
Pascal
<lang Pascal>program StringAppend; {$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes { you can add units after this };
var
s: String = 'Hello';
begin
s += ' World !'; WriteLn(S); ReadLn;
end.</lang> Output:
Hello World !
Perl
<lang perl>my $str = 'Foo'; $str .= 'bar'; print $str;</lang>
- Output:
Foobar
Perl 6
<lang perl6>my $str = "foo"; $str ~= "bar"; say $str;</lang>
- Output:
foobar
Phix
<lang Phix>string s = "this string" ?s s &= " is now longer" ?s</lang>
- Output:
"this string" "this string is now longer"
PicoLisp
<lang picolisp>(setq Str1 "12345678") (setq Str1 (pack Str1 "9!")) (println Str1)</lang>
- Output:
"123456789!"
PL/I
<lang PL/I>Cat: procedure options (main);
declare s character (100) varying; s = 'dust '; s ||= 'bowl'; put (s);
end Cat;</lang>
dust bowl
PowerShell
<lang PowerShell> $str = "Hello, " $str += "World!" $str </lang>
Hello, World!
PureBasic
<lang purebasic>S$ = "Hello" S$ = S$ + " Wo" ;by referencing the string twice S$ + "rld!" ;by referencing the string once If OpenConsole()
PrintN(S$)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole()
EndIf</lang> Sample output:
Hello World!
Python
File: String_append.py<lang python>#!/usr/bin/env python
- -*- coding: utf-8 -*- #
str = "12345678"; str += "9!"; print(str)</lang>
- Output:
123456789!
Racket
<lang racket>;there is no built-in way to set! append in racket (define mystr "foo") (set! mystr (string-append mystr " bar")) (displayln mystr)
- but you can create a quick macro to solve that problem
(define-syntax-rule (set-append! str value)
(set! str (string-append str value)))
(define mymacrostr "foo") (set-append! mymacrostr " bar") (displayln mystr)</lang>
- Output:
foo bar foo bar
REXX
using abutment
<lang rexx>s='he' s=s'llo world!' Say s</lang> output
hello world!
using concatenation
<lang rexx>s="He" s=s || 'llo, World!' /*same as: s=s||'llo, World!' */ say s</lang> output
Hello, World!
Ring
<lang ring> aString1 = "Welcome to the " aString2 = "Ring Programming Language" aString3 = aString1 + aString2 see aString3 </lang>
Ruby
<lang ruby>s = "Hello wo" s += "rld" # new string object s << "!" # mutates in place, same object puts s</lang>
- Output:
Hello world!
Scala
An evaluation in Scala worksheet. <lang scala> var d = "Hello" // Mutables are discouraged //> d : String = Hello
d += ", World!" // var contains a totally new re-instantiationed String
val s = "Hello" // Immutables are recommended //> s : String = Hello val s1 = s + s //> s1 : String = HelloHello val f2 = () => " !" //Function assigned to variable //> f2 : () => String = <function0> println(s1 + f2()); //> HelloHello !</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
local var string: str is "12345678"; begin str &:= "9!"; writeln(str); end func;</lang>
- Output:
123456789!
Sidef
<lang ruby>var str = 'Foo'; str += 'bar'; say str;</lang>
- Output:
Foobar
SNOBOL4
<lang SNOBOL4> s = "Hello"
s = s ", World!" OUTPUT = s
END</lang>
- Output:
Hello, World!
Swift
<lang swift>var s = "foo" // "foo" s += "bar" // "foobar" print(s) // "foobar" s.appendContentsOf("baz") // "foobarbaz" print(s) // "foobarbaz"</lang>
Tcl
String concatenation is a fundamental feature of the Tcl language, and there is also an append
that makes concatenation even simpler:
<lang tcl>set s "he"
set s "${s}llo wo"; # The braces distinguish varname from text to concatenate
append s "rld"
puts $s</lang>
- Output:
hello world
Ursa
<lang ursa>decl string str set str "hello "
- append "world" to str
set str (+ str "world")
- outputs "hello world"
out str endl console</lang>
VBA
<lang VB>Function StringAppend() Dim s As String s = "foo" s = s & "bar" Debug.Print s End Function</lang>
VBScript
<lang vb>s = "Rosetta" s = s & " Code" WScript.StdOut.Write s</lang>
- Output:
Rosetta Code
Wart
<lang python>s <- "12345678" s <- (s + "9!")</lang>
zkl
zkl strings are immutable, but byte blobs are mutable. <lang zkl>var s="foo"; s+="bar"; //-->new string "foobar" s.append("bar"); //-->new string "foobar", same as above
s=Data(Void,"foo"); s.append("bar"); // or s+="bar" s.text; //-->"foobar"</lang>
- Programming Tasks
- Basic language learning
- String manipulation
- Basic Data Operations
- Simple
- ALGOL 68
- AutoHotkey
- AWK
- Axe
- BASIC
- Applesoft BASIC
- BBC BASIC
- Bracmat
- C
- C++
- C sharp
- Clojure
- COBOL
- CoffeeScript
- Common Lisp
- D
- EchoLisp
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Forth
- Fortran
- Go
- Icon
- Unicon
- Haskell
- J
- Java
- JavaScript
- Jq
- Julia
- Lasso
- Lingo
- LiveCode
- Lua
- Maple
- Mathematica
- NetRexx
- NewLISP
- Nim
- Objeck
- OCaml
- Oforth
- PARI/GP
- Pascal
- Perl
- Perl 6
- Phix
- PicoLisp
- PL/I
- PowerShell
- PureBasic
- Python
- Racket
- REXX
- Ring
- Ruby
- Scala
- Seed7
- Sidef
- SNOBOL4
- Swift
- Tcl
- Ursa
- VBA
- VBScript
- Wart
- Zkl
- Bc/Omit
- Dc/Omit