String prepend: Difference between revisions
Added various BASIC dialects (Chipmunk Basic, GW-BASIC, MSX Basic and Quite BASIC)
(Added various BASIC dialects (Chipmunk Basic, GW-BASIC, MSX Basic and Quite BASIC)) |
|||
(63 intermediate revisions by 44 users not shown) | |||
Line 17:
To illustrate the operation, show the content of the variable.
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V s = ‘12345678’
s = ‘0’s
print(s)</syntaxhighlight>
{{out}}
<pre>
012345678
</pre>
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* String prepend - 14/04/2020
PREPEND CSECT
USING PREPEND,13 base register
B 72(15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST 13,4(15) link backward
ST 15,8(13) link forward
LR 13,15 set addressability
MVC C+L'B(L'A),A c=a
MVC C(L'B),B c=b+c (prepend)
XPRNT C,L'C print buffer
L 13,4(0,13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
A DC C'world!' a
B DC C'Hello ' b
C DC CL80' ' c
END PREPEND</syntaxhighlight>
{{out}}
<pre>
Hello world!
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program appendstr64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessString: .asciz "British Museum.\n"
szComplement: .skip 80
szStringStart: .asciz "The rosetta stone is at "
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszMessString
ldr x1,qAdrszStringStart
bl prepend // append sting2 to string1
ldr x0,qAdrszMessString
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessString: .quad szMessString
qAdrszStringStart: .quad szStringStart
qAdrszCarriageReturn: .quad szCarriageReturn
/**************************************************/
/* append two strings */
/**************************************************/
/* x0 contains the address of the string1 */
/* x1 contains the address of the string2 */
prepend:
stp x1,lr,[sp,-16]! // save registers
mov x3,#0 // length counter
1: // compute length of string 1
ldrb w4,[x0,x3]
cmp w4,#0
cinc x3,x3,ne // increment to one if not equal
bne 1b // loop if not equal
mov x5,#0 // length counter insertion string
2: // compute length of insertion string
ldrb w4,[x1,x5]
cmp x4,#0
cinc x5,x5,ne // increment to one if not equal
bne 2b
cmp x5,#0
beq 99f // string empty -> error
add x3,x3,x5 // add 2 length
add x3,x3,#1 // +1 for final zero
mov x6,x0 // save address string 1
mov x0,#0 // allocation place heap
mov x8,BRK // call system 'brk'
svc #0
mov x5,x0 // save address heap for output string
add x0,x0,x3 // reservation place x3 length
mov x8,BRK // call system 'brk'
svc #0
cmp x0,#-1 // allocation error
beq 99f
mov x4,#0 // counter byte string 2
3:
ldrb w3,[x1,x4] // load byte string 2
cbz x3,4f // zero final ?
strb w3,[x5,x4] // store byte string 2 in heap
add x4,x4,1 // increment counter 1
b 3b // no -> loop
4:
mov x2,#0 // counter byte string 1
5:
ldrb w3,[x6,x2] // load byte string 1
strb w3,[x5,x4] // store byte string in heap
cbz x3,6f // zero final ?
add x2,x2,1 // no -> increment counter 1
add x4,x4,1 // no -> increment counter 2
b 5b // no -> loop
6: // recopie heap in string 1
mov x2,#0 // counter byte string
7:
ldrb w3,[x5,x2] // load byte string in heap
strb w3,[x6,x2] // store byte string 1
cbz x3,100f // zero final ?
add x2,x2,1 // no -> increment counter 1
b 7b // no -> loop
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
British Museum.
The rosetta stone is at British Museum.
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Append(CHAR ARRAY text,suffix)
BYTE POINTER srcPtr,dstPtr
BYTE len
len=suffix(0)
IF text(0)+len>255 THEN
len=255-text(0)
FI
IF len THEN
srcPtr=suffix+1
dstPtr=text+text(0)+1
MoveBlock(dstPtr,srcPtr,len)
text(0)==+suffix(0)
FI
RETURN
PROC Prepend(CHAR ARRAY text,prefix)
CHAR ARRAY tmp(256)
SCopy(tmp,text)
SCopy(text,prefix)
Append(text,tmp)
RETURN
PROC TestPrepend(CHAR ARRAY text,preffix)
PrintF("Source ""%S"" at address %H%E",text,text)
PrintF("Prepend ""%S""%E",preffix)
Prepend(text,preffix)
PrintF("Result ""%S"" at address %H%E",text,text)
PutE()
RETURN
PROC Main()
CHAR ARRAY text(256)
text(0)=0
TestPrepend(text,"World!")
TestPrepend(text,"Hello ")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_prepend.png Screenshot from Atari 8-bit computer]
<pre>
Source "" at address $2A8A
Prepend "World!"
Result "World!" at address $2A8A
Source "World!" at address $2A8A
Prepend "Hello "
Result "Hello World!" at address $2A8A
</pre>
=={{header|Ada}}==
Line 22 ⟶ 233:
In Ada, a variable of type String cannot change its length. So the variable S which we will change, need to be of the type Unbounded_String. Thus the need for conversions from String literal to Unbounded_String for initialization, and from Unbounded_String to String for printing.
<
procedure Prepend_String is
Line 29 ⟶ 240:
S := "Hello " & S;-- this is the operation to prepend "Hello " to S.
Ada.Text_IO.Put_Line(To_String(S));
end Prepend_String;</
{{out}}
Line 39 ⟶ 250:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.7 algol68g-2.7].}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards).}}
'''File: String_prepend.a68'''<
# -*- coding: utf-8 -*- #
STRING str := "12345678";
"0" +=: str;
print(str)</
{{out}}
<pre>
012345678
</pre>
=={{header|AppleScript}}==
AppleScript text is immutable, so prepending is only possible by creating a new text through concatenation of the variable's existing contents to the other string:
<syntaxhighlight lang="applescript">set aVariable to "world!"
set aVariable to "Hello " & aVariable
return aVariable</syntaxhighlight>
{{output}}
<syntaxhighlight lang="applescript">"Hello world!"</syntaxhighlight>
It's a similar situation with NSString class in AppleScriptObjC. This has various ways of achieving the same thing, probably the most sensible of which is the first of the following:
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
set aVariable to current application's class "NSString"'s stringWithString:("world!")
set aVariable to aVariable's stringByReplacingCharactersInRange:({0, 0}) withString:("Hello ")
-- return aVariable as text
-- Or:
set aVariable to current application's class "NSString"'s stringWithString:("world!")
set aVariable to current application's class "NSString"'s stringWithFormat_("%@%@", "Hello ", aVariable)
-- return aVariable as text
-- Or:
set aVariable to current application's class "NSString"'s stringWithString:("world!")
set aVariable to aVariable's stringByReplacingOccurrencesOfString:("^") withString:("Hello ") ¬
options:(current application's NSRegularExpressionSearch) range:({0, 0})
-- return aVariable as text</syntaxhighlight>
But there's also an NS''Mutable''String class. This has 'replace' versions of the 'stringByReplacing' methods above and also this <tt>insertString:atIndex:</tt> method:
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
set aVariable to current application's class "NSMutableString"'s stringWithString:("world!")
tell aVariable to insertString:("Hello ") atIndex:(0)
return aVariable as text</syntaxhighlight>
{{output}}
<syntaxhighlight lang="applescript">"Hello world!"</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: "World"
a: "Hello" ++ a
print a
b: "World"
b: append "Hello" b
print a
c: "World"
prefix 'c "Hello"
print c
d: "World"
print prefix d "Hello"</syntaxhighlight>
{{out}}
<pre>HelloWorld
HelloWorld
HelloWorld
HelloWorld</pre>
=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">string s1 = " World!";
write("Hello" + s1);
write("Hello", s1);
string s2 = "Hello" + s1;
write(s2);</syntaxhighlight>
=={{header|AutoHotkey}}==
<
s := s "bar"
Msgbox % s</
{{out}}
<pre>
Line 60 ⟶ 344:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f STRING_PREPEND.AWK
BEGIN {
Line 68 ⟶ 352:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
foobar
</pre>
=={{header|BaCon}}==
<syntaxhighlight lang="bacon">s$ = "prepend"
s$ = "String " & s$
PRINT s$</syntaxhighlight>
{{out}}
<pre>String prepend</pre>
=={{header|BASIC}}==
<
S$ = "Hello" + S$
PRINT S$
</syntaxhighlight>
{{out}}
<pre>Hello World!</pre>
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoft basic">100 LET S$=" World!"
110 LET S$="Hello"+S$
120 PRINT S$</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">a$ = " World!"
a$ = "Hello"; a$
print a$
# would also be valid
a$ = "Hello" + a$
# and
a$ = "Hello" & a$</syntaxhighlight>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|GW-BASIC}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">10 A$ = " World!"
20 A$ = "Hello" + A$
30 PRINT A$</syntaxhighlight>
==={{header|
{{works with|
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">10 A$ = " World!"
20 A$ = "Hello" + A$
30 PRINT A$</syntaxhighlight>
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 LET S$=" World!"
110 LET S$="Hello"&S$
120 PRINT S$</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 A$ = " World!"
20 A$ = "Hello" + A$
30 PRINT A$</syntaxhighlight>
==={{header|Run BASIC}}===
{{works with|BASIC256}}
{{works with|Liberty BASIC}}
{{works with|QB64}}
{{works with|QBasic}}
{{works with|Yabasic}}
<syntaxhighlight lang="runbasic">a$ = " World!"
a$ = "Hello" + a$
print a$
' en RB, LB and BASIC256 would also be valid
a$ = "Hello"; a$</syntaxhighlight>
==={{header|Quite BASIC}}===
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 LET A$ = " World!"
20 LET A$ = "Hello" + A$
30 PRINT A$</syntaxhighlight>
==={{header|True BASIC}}===
{{works with|BASIC256}}
<syntaxhighlight lang="qbasic">LET a$ = " World!"
LET a$ = "Hello" & a$
PRINT a$
END</syntaxhighlight>
==={{header|Yabasic}}===
{{works with|BASIC256}}
{{works with|Liberty BASIC}}
{{works with|QB64}}
{{works with|QBasic}}
{{works with|Run BASIC}}
<syntaxhighlight lang="freebasic">a$ = " World!"
a$ = "Hello" + a$
print a$</syntaxhighlight>
=={{header|Binary Lambda Calculus}}==
BLC program
<pre>18 16 46 80 05 bc bc fd f6 e0 67 6d 61</pre>
based on https://github.com/tromp/AIT/blob/master/rosetta/catstrings.lam
prepends "ma" to "gma" to output "magma".
=={{header|Bracmat}}==
<
& str$("Hello " !string):?string
& out$!string</
<pre>Hello World!</pre>
=={{header|C}}==
<
#include<string.h>
#include<stdlib.h>
Line 108 ⟶ 492:
printf("%s\n",str);
return 0;
}</
{{out}}
<pre>Changed my String</pre>
=={{header|C sharp}}==
<
namespace PrependString
Line 144 ⟶ 511:
}
}
}</
<pre>Hello World</pre>
=={{header|C++}}==
<syntaxhighlight lang="cpp">include <vector>
#include <algorithm>
#include <string>
#include <iostream>
int main( ) {
std::vector<std::string> myStrings { "prepended to" , "my string" } ;
std::string prepended = std::accumulate( myStrings.begin( ) ,
myStrings.end( ) , std::string( "" ) , []( std::string a ,
std::string b ) { return a + b ; } ) ;
std::cout << prepended << std::endl ;
return 0 ;
}</syntaxhighlight>
{{out}}
<pre>prepended tomy string</pre>
=={{header|Clojure}}==
===A pure function implementation with immutability ===
<syntaxhighlight lang="clojure">
(defn str-prepend [a-string, to-prepend]
(str to-prepend a-string))
</syntaxhighlight>
=== REPL demonstrations with mutability in mind ===
a) with the atom data structure
<syntaxhighlight lang="clojure">
(def s (atom "World"))
(swap! s #(str "Hello, " %))
user=> @s
user=> "Hello, Wolrd"
</syntaxhighlight>
b) with the ref data structure
<syntaxhighlight lang="clojure">
(def s (ref "World"))
(dosync (alter s #(str "Hello " %)))
user=> @s
user=> "Hello World"
</syntaxhighlight>
=={{header|COBOL}}==
<
program-id. prepend.
data division.
Line 179 ⟶ 584:
move function reverse (str (1:len)) to str
.
end program prepend.</
<pre>Hello World!</pre>
{{works with|GNU Cobol|2.0}}
<
PROGRAM-ID. prepend.
Line 193 ⟶ 598:
DISPLAY str
.
END PROGRAM prepend.</
=={{header|ColdFusion}}==
=== Classic tag based CFML ===
<
<cfoutput>
<cfset who = "World!">
#"Hello " & who#
</cfoutput>
</syntaxhighlight>
{{Output}}
<pre>
Line 209 ⟶ 614:
=== Script Based CFML ===
<
who = "World!";
greeting = "Hello " & who;
writeOutput( greeting );
</cfscript></
{{Output}}
<pre>
Line 221 ⟶ 626:
=={{header|Common Lisp}}==
A macro is necessary in order to prepend a string in-place:
<
"Prepend the given string variable with additional strings. The string variable is modified in-place."
`(setf ,s (concatenate 'string ,@strs ,s)))
Line 227 ⟶ 632:
(defvar *str* "foo")
(prependf *str* "bar")
(format T "~a~%" *str*)</
{{out}}
<pre>barfoo</pre>
=={{header|D}}==
<
void main() {
Line 238 ⟶ 643:
s = "Hello " ~ s;
writeln(s);
}</
{{out}}
<pre>Hello world!</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
program String_preappend;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TStringHelper = record helper for string
procedure Preappend(str: string);
end;
{ TStringHelper }
procedure TStringHelper.Preappend(str: string);
begin
Self := str + self;
end;
begin
var h: string;
// with + operator
h := 'World';
h := 'Hello ' + h;
writeln(h);
// with a function concat
h := 'World';
h := concat('Hello ', h);
writeln(h);
// with helper
h := 'World';
h.Preappend('Hello ');
writeln(h);
readln;
end.</syntaxhighlight>
{{out}}
<pre>Hello World
Hello World
Hello World</pre>
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">var s = "world!"
s = "Hello " + s
print(s)</syntaxhighlight>
=={{header|Déjà Vu}}==
<
set :s concat( "Hello " s)
!print s</
{{out}}
<pre>Hello world!</pre>
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
string$ = "Lang"
string$ = "Easy" & string$
print string$
</syntaxhighlight>
{{out}}
<pre>EasyLang</pre>
=={{header|EchoLisp}}==
<
define-syntax-rule
(set!-string-prepend a before)
Line 261 ⟶ 726:
name
→ "Elvis Presley"
</syntaxhighlight>
=={{header|Elena}}==
ELENA
<
import extensions'text
public program()
{
var s := "World"
s := "Hello " + s
console
// Alternative way
var s2 :=
s2.insert(0,
console
console
}</syntaxhighlight>
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">
str1 = "World!"
str = "Hello, " <> str1
</syntaxhighlight>
{{out}}
Line 291 ⟶ 756:
=={{header|Emacs Lisp}}==
While strings in Emacs Lisp are mutable, they're fixed size. Therefore the <code>concat</code> function creates a new string and the existing string must be referenced twice:
<syntaxhighlight lang="lisp">(defvar str "bar")
(setq str (concat "foo" str))
str ;=> "foobar"</syntaxhighlight>
This can be hidden by using a macro such as <code>cl-callf2</code> which expands into the above code:
{{libheader|cl-lib}}
<syntaxhighlight lang="lisp">(require 'cl-lib)
(
(
str ;=> "foobar"</syntaxhighlight>
Buffers can be thought of as expandable strings:
<syntaxhighlight lang="lisp">(let ((buf (get-buffer-create "*foo*")))
(with-current-buffer buf
(insert "bar"))
(with-current-buffer buf
(goto-char (point-min))
(insert "foo")
(buffer-string)))
;; => "foobar"</syntaxhighlight>
=={{header|EMal}}==
<syntaxhighlight lang="emal">
text greeting = "world"
^|basic concatenation|^
writeLine("hello " + greeting)
^|changing the text in place|^
writeLine(greeting.insert(0, "hello "))
writeLine(greeting)
</syntaxhighlight>
{{out}}
<pre>
hello world
hello world
hello world
</pre>
Line 322 ⟶ 809:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
......
S$=" World!"
Line 328 ⟶ 815:
PRINT(S$)
......
</syntaxhighlight>
{{out}}
<pre>Hello World!</pre>
=={{header|F Sharp|F#}}==
<
s <- "Hello, " + s
printfn "%s" s</
=={{header|Factor}}==
<
"world"
"Hello " prepend
</syntaxhighlight>
=={{header|Falcon}}==
'''VBA/Python programmer's approach not sure if it's the most falconic way'''
<
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 354 ⟶ 840:
s = s + "Falcon"
> s
</syntaxhighlight>
{{out}}
<pre>
Line 364 ⟶ 850:
Forth has no string prepend word, but adding it is not difficult. This demonstration starts from the low level operations that Forth gives us and quickly builds a simple set of "WORDS" (sub-routines) that let us move strings from address to address. Strings are just an address on the data stack so we can reference them as many times as we need to. Our prepend word makes use of the Return stack as a temporary storage for the address of the string we want to prepend. Standard Forth also provides a named general purpose buffer called PAD, so we make use of that too. With this PREPEND becomes part of the language.
<syntaxhighlight lang="text">\ the following functions are commonly native to a Forth system. Shown for completeness
: C+! ( n addr -- ) dup c@ rot + swap c! ; \ primitive: increment a byte at addr by n
Line 382 ⟶ 868:
R> ; \ leave a copy of addr2 on the data stack
: writeln ( addr -- ) cr count type ; \ syntax sugar for testing</
Test our language extensions interactively at the console
Line 398 ⟶ 884:
===Initial difficulty===
With Fortran IV came the ability to use arrays of integers and the A1 format code in READ and WRITE statements for them. With sixteen-bit integers, one might use A2 and so forth, but the numerical values of the integers would not be convenient especially if the sign bit was involved. This would be even more difficult with floating-point variables. Still, the desire for good headings and annotations and flexible layout flogged one onwards. Following the Pascal "Hello world!" example, one might proceed somewhat as follows:<
DATA TEXT(1),TEXT(2),TEXT(3)/"Wo","rl","d!"/
Line 412 ⟶ 898:
WRITE (6,3) (TEXT(I), I = 1,6)
3 FORMAT (66A2)
END</
This old-style source is acceptable to the F90 compiler as it stands. By chance, two characters per integer fits nicely but in many cases having one character per variable is easier for manipulation. So, as usual with Fortran, it's all done with arrays. The DATA statement demonstrates that a quoted string is acceptable as a value for an integer; it is just a matter of bit patterns, and this type miscegnation will work with floating-point variables also though resulting in even stranger numerical values. Looking more closely, note that an INTEGER*4 variable can hold four eight-bit characters but only two-character text literals have been specified. Unlike integer constants, which might be considered to have leading zero digits, text literals are deemed to have trailing spaces as needed: <code>"Wo"</code> is deemed to be <code>"Wo "</code> to make up to the recipient's capacity for four characters, and when format code A2 is specified, the leftmost two characters in the variable are taken. The strange ideas of "little-endianism" have never flourished on mainframes! Thus, if the format code were to be A4, then "Wo " would appear, not " Wo".
Line 427 ⟶ 913:
===Character facility===
With F77 came the CHARACTER type... <
TEXT = "World!"
TEXT = "Hello "//TEXT
WRITE (6,*) TEXT
END </
This means that variable TEXT has space for 66 characters, addressed as TEXT(''first'':''last'') starting with one. There is no associated string length facility, so the first assignment places the six characters of the supplied literal, followed by spaces all the way to the end of TEXT. Alternatively, <code>TEXT(1:6) = "World!"</code> would place only six characters, leaving the rest of TEXT to hold whatever it may. This would probably be unsuitable for the next statement, which prepends "Hello " to the content of TEXT (including positions past six) and assigns the result to TEXT, overwriting its previous content - with the aid of a temporary working area. Although in principle there could be cunning schemes that update the recipient "in place" with a minimum of character copying to and fro, this doesn't happen. Only characters up to the capacity of the recipient will be transferred from the expression's result, and if the result is shorter than the capacity of the recipient, trailing spaces will be added. All of this is extra effort! And when TEXT is written out, all 66 characters will be sent forth. It is useful to have a function that locates the last non-blank character!
Line 438 ⟶ 924:
=={{header|FreeBASIC}}==
<
Var s = "prepend"
s = "String " + s
Print s
Sleep</
{{out}}
Line 449 ⟶ 935:
String prepend
</pre>
=={{header|Free Pascal}}==
Free Pascal supports everything shown in [[#Pascal|§ Pascal]] (except the <tt>string</tt> schema data type, <tt>string(20)</tt> must be written like here).
Furthermore, using the compiler directive <tt>{$COperators}</tt> the following is possible, too:
<syntaxhighlight lang="delphi">var
line: string[20];
begin
line := 'Hello ';
{$COperators on}
line += 'world!';
writeLn(line)
end.</syntaxhighlight>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
void local fn DoIt
CFStringRef s = @"world!"
s = fn StringByAppendingString( @"Hello ", s )
NSLog(@"%@",s)
end fn
fn DoIt
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
Hello world!
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=cd5ab867c22e872d69ed81fd9da96707 Click this link to run this code]'''
<
Dim sString1 As String = "world!"
Dim sString2 As String = "Hello "
Line 459 ⟶ 978:
Print sString1
End</
Output:
<pre>
Line 466 ⟶ 985:
=={{header|Go}}==
<
s = "Hello, " + s</
=={{header|Haskell}}==
<
Prelude> let f = (++" World!")
Prelude> f "Hello"
</syntaxhighlight>
{{out}}
Line 480 ⟶ 999:
=={{header|Icon}} and {{header|Unicon}}==
<
s := "Hello, " || s</
To demonstrate how this could be done with only one reference to the variable during the prepend:
<syntaxhighlight lang="unicon">procedure main()
s := ", world"
s[1:1] ||:= "Hello"
write(s)
end</syntaxhighlight>
{{out}}
<pre>prompt$ unicon -s prepend.icn -x
Hello, world</pre>
Another take on it, using String Scanning:
<syntaxhighlight lang="unicon">procedure main()
(s := ", world") ?:= "Hello" || tab(0)
write(s)
end</syntaxhighlight>
{{out}}
<pre>prompt$ unicon -s prepend.icn -x
Hello, world</pre>
=={{header|J}}==
<
s
value
s=: 'new ',s
s
new value</
=={{header|Java}}==
Java does not have a prepend method.<br />
The most logical way to prepend a string value is with basic concatenation.
<syntaxhighlight lang="java">
string = "abc" + string;
</syntaxhighlight>
You could also use the ''String.concat'' method.
<syntaxhighlight lang="java">
String string = "def";
string = "abc".concat(string);
</syntaxhighlight>
You could use the ''StringBuilder'' class which provides an ''insert'' method.
<syntaxhighlight lang="java">
StringBuilder string = new StringBuilder();
string.append("def");
string.insert(0, "abc");
</syntaxhighlight>
Additionally, you could use the ''String.format'' or ''String.formatted'' methods.
<syntaxhighlight lang="java">
String string = "def";
string = String.format("abc%s", string);
</syntaxhighlight>
<syntaxhighlight lang="java">
String string = "def";
string = "abc%s".formatted(string);
</syntaxhighlight>
All of these will produce the following output.
<pre>
abcdef
</pre>
=={{header|Javascript}}==
<
var s=", World"
s = "Hello" + s
print(s);</
=={{header|jq}}==
<
| "Hello " + $s</
=={{header|Julia}}==
<
s = "Hello " * s</
=={{header|K}}==
<syntaxhighlight lang="k">
s: "world!"
"world!"
"Hello " , s
"Hello world!"
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 538 ⟶ 1,100:
t = t.prependIndent("Donald ")
println(t)
}</
{{out}}
Line 545 ⟶ 1,107:
Donald Trump
</pre>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def str World}
-> str
Hello, {str}
-> Hello, World
</syntaxhighlight>
=={{header|Lasso}}==
<
#x->merge(1,'Hello')
#x // Hello, World!</
=={{header|LFE}}==
Line 555 ⟶ 1,126:
Using the concatenation operator:
<
> (set s "world")
"world"
> (++ "hello " s)
"hello world"
</syntaxhighlight>
Using the concatenation function:
<
> (set s "world")
"world"
> (string:concat "hello " s)
"hello world"
</syntaxhighlight>
=={{header|Lingo}}==
<
put "Hello " before str
put str
-- "Hello world!"</
=={{header|LiveCode}}==
The idiomatic way is to use "before"<
put "hello" before x
put x // hello world</
=={{header|Lua}}==
Line 586 ⟶ 1,157:
By concatenation:
<
s = "12345678"
s = "0" .. s
print(s)</
By string formatting:
<
s = "12345678"
s = string.format("%s%s", "0", s)
print(s)</
By list joining:
<
s = "12345678"
s = table.concat({"0", s})
print(s)</
{{out}} of each solution:
Line 609 ⟶ 1,180:
012345678
</pre>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module PrependString {
A$="Hello"
Line 617 ⟶ 1,189:
}
PrependString
</syntaxhighlight>
{{out}}
Line 625 ⟶ 1,197:
=={{header|Maple}}==
<
m := cat("Hello", l);
n := "Hello"||l;
o := `||`("Hello", l);</
{{out}}
<pre>
Line 637 ⟶ 1,209:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
a = "another string literal" <> a (* using concatenation (no built-in prepend) *)</
{{out}}
<pre>"another string literalany text value"</pre>
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 652 ⟶ 1,224:
main(!IO) :-
S = "World!\n",
io.write_string("Hello " ++ S, !IO).</
{{out}}
<pre>
Hello World!
</pre>
=={{header|Nanoquery}}==
Nanoquery has no idiomatic way to prepend one string to another.
<syntaxhighlight lang="nanoquery">s1 = " a test"
s1 = "this is" + s1
println s1</syntaxhighlight>
{{out}}
<pre>this is a test</pre>
=={{header|Neko}}==
The plus operator, +, concatenates string data. Neko treats strings as mutable fixed length buffers, so some care would need to be taken when prepending variables to variables as there may be buffer sizing to take into consideration. For literals, this is not a concern, as the literals are placed in buffers of the proper size by the compiler.
<syntaxhighlight lang="actionscript">/**
<doc><p>String prepend in Neko</pre></doc>
**/
var str = ", world"
str = "Hello" + str
$print(str, "\n")</syntaxhighlight>
{{out}}
<pre>prompt$ nekoc string-prepend.neko
prompt$ neko string-prepend.n
Hello, world</pre>
=={{header|NetRexx}}==
<
s_ = 'Hello, 's_
say s_</
{{out}}
<pre>
Line 668 ⟶ 1,265:
=={{header|NewLISP}}==
<
(push "foo" str)
(println str)</
=={{header|Nim}}==
<syntaxhighlight lang
var str1, str2 = "12345678"
str1 = "0" & str1
echo str1
# Using "insert".
str2.insert("0")
echo str2
</syntaxhighlight>
{{out}}
<pre>012345678
012345678</pre>
=={{header|Objeck}}==
<
function : Main(args : String[]) ~ Nil {
s := "world!";
"Hello {$s}"->PrintLine();
}
}</
<pre>
Hello World!
</pre>
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let () =
let s = ", world" in
let s = "Hello" ^ s in
print_endline s</syntaxhighlight>
=={{header|Oforth}}==
<
{{out}}
Line 700 ⟶ 1,313:
=={{header|PARI/GP}}==
Not supported in GP.
<
s = Str("Hello, ", s)</
{{out}}
<pre>%1 = "Hello, world!"</pre>
=={{header|Pascal}}==
''See also [[#Free Pascal|Free Pascal]]''
{{works with|Extended Pascal}}
<syntaxhighlight lang="pascal">program stringPrepend(output);
var
line: string(20);
begin
line := line + 'world!';
writeLn(line);
line := 'Hello ';
writeStr(line, line, 'world!');
writeLn(line)
end.</syntaxhighlight>
{{out}}
<pre>Hello
Hello world!</pre>
=={{header|Perl}}==
<
use warnings;
use feature ':all';
Line 750 ⟶ 1,359:
$_ = 'bar';
$_ = "Foo$_";
say;</
{{out}}
Line 759 ⟶ 1,368:
</pre>
=={{header|
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"World"</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Hello "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s</span>
<!--</syntaxhighlight>-->
<b>NB:</b> s = prepend(s,"Hello ") gives typecheck: s is {"Hello ",87'W',111'o',114'r',108'l',100'd'}, of length 6, rather than the "Hello World" of length 11 you probably wanted.<br>
- and likewise s = prepend("Hello ",s) is not only the wrong way round but dies with typecheck: s is {"World",72'H',101'e',108'l',108'l',111'o',32' '} (length 7).
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_prepend
by Galileo, 10/2022 #/
"Hello " var s
s "world" chain var s
s print</syntaxhighlight>
=={{header|Picat}}==
As usual there are a couple ways of doing this. The most common is probable to use string concatenation (<code>++</code>), but <code>append/3</code> might be useful if backtracking is needed.
<syntaxhighlight lang="picat">go =>
S = "123456789",
println(S),
S := "A" ++ S,
println(S),
% append
append("B",S,T),
S := T,
println(S),
% insert at position
S := insert(S,1,'C'), % note: must be a char to keep it a proper string
println(S),
% insert many characters
S := insert_all(S,1,"DE"),
println(S),
nl.</syntaxhighlight>
{{out}}
<pre>
A123456789
BA123456789
CBA123456789
=={{header|PicoLisp}}==
<
(setq Str1 (pack "0" Str1))
(println Str1)</
{{out}}
<pre>
Line 806 ⟶ 1,424:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
Pre_Cat: procedure options (main); /* 2 November 2013 */
declare s character (100) varying;
Line 813 ⟶ 1,431:
put (s);
end Pre_Cat;
</syntaxhighlight>
<pre>
dust bowl
Line 819 ⟶ 1,437:
=={{header|PlainTeX}}==
<
\def\tempstring{#1}%
\expandafter\expandafter\expandafter
Line 829 ⟶ 1,447:
\prepend{Hello }\mystring
Result : \mystring
\bye</
Here is an equivalent code with eTeX capabilities:
<
\edef#2{\unexpanded{#1}\unexpanded\expandafter{#2}}%
}
Line 838 ⟶ 1,456:
\prepend{Hello }\mystring
Result : \mystring
\bye</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$str = "World!"
$str = "Hello, " + $str
$str
</syntaxhighlight>
<pre>Hello, World!</pre>
Line 860 ⟶ 1,478:
the string. I define an operator for the purpose:
<
:- op(200, xfx, user:(=+)).
Line 873 ⟶ 1,491:
nb_setarg(2, Chars, Rest),
nb_setarg(1, Chars, X).
</syntaxhighlight>
Example of this abomination in action:
<
?- Str = `World!`, `Hello, ` =+ Str.
Str = "Hello, World!".</
Note: I can't imagine when I would want to do this in Prolog.
=={{header|PureBasic}}==
<
S$ = "Hello" + S$
If OpenConsole()
Line 891 ⟶ 1,509:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>Hello World!</pre>
Line 898 ⟶ 1,516:
'''File: string_prepend.py'''
<
# -*- coding: utf-8 -*-
s = "12345678"
s = "0" + s # by concatenation
print(s)</
{{out}}
Line 909 ⟶ 1,527:
012345678
</pre>
=={{header|QB64}}==
<syntaxhighlight lang="qbasic">s$ = "prepend"
s$ = "String " + s$
Print s$</syntaxhighlight>
{{out}}
<pre>String prepend</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">$ "with a rubber duck."
$ "One is never alone "
swap join
echo$</syntaxhighlight>
{{out}}
<pre>One is never alone with a rubber duck.</pre>
=={{header|Racket}}==
<
(define str "foo")
(set! str (string-append "bar " str))
Line 923 ⟶ 1,559:
(set-prepend! macrostr "foo")
(displayln macrostr)
</syntaxhighlight>
{{out}}
<pre>bar foo
foo bar</pre>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line># explicit concatentation
$_ = 'byte';
$_ = 'kilo' ~ $_;
.say;
# interpolation as concatenation
$_ = 'buck';
$_ = "mega$_";
.say;
# lvalue substr
$_ = 'bit';
substr-rw($_,0,0) = 'nano';
.say;
# regex substitution
$_ = 'fortnight';
s[^] = 'micro';
.say;
# reversed append assignment
$_ = 'cooper';
$_ [R~]= 'mini';
.say;</syntaxhighlight>
{{out}}
<pre>kilobyte
megabuck
nanobit
microfortnight
minicooper</pre>
=={{header|Red}}==
<
s: "world"
insert s "hello "
print s
</syntaxhighlight>
{{out}}
<pre>hello world</pre>
=={{header|REXX}}==
<
zz= 'he'zz /*This won't work if the variable name is X or B */
say zz
Line 949 ⟶ 1,620:
bString= "he"
aString= bString || aString
say aString</
'''output'''
<pre>
Line 958 ⟶ 1,629:
=={{header|Ring}}==
<
aString = "World!"
bString = "Hello, " + aString
see bString + nl
</syntaxhighlight>
=={{header|RPL}}==
In HP-48+ RPL versions, the <code>STO+</code> instruction can either append or prepend a string to a variable containing already a string.
"def" '<span style="color:green">Z</span>' STO
"abc" '<span style="color:green">Z</span>' STO+
<span style="color:green">Z</span>
'''Output'''
<span style="color:grey"> 1:</span> "abcdef"
=={{header|Ruby}}==
There is a method for prepending a string, aptly named "prepend".
<
str.prepend("He")
p str #=> "Hello world"</
=={{header|Rust}}==
<
let mut s = "World".to_string();
s.insert_str(0, "Hello ");
println!("{}", s);
</syntaxhighlight>
=={{header|Scala}}==
Evaluation in Scala worksheet
<
val f2 = () => ", " //Function assigned to variable
//> f2 : () => String = <function0>
val s1 = "Hello" + f2() + s //> s1 : String = Hello, World
println(s1); //> Hello, World</
=={{header|sed}}==
There are no variables in ''sed'', just two distinct locations for storing a string: The "pattern space" and the "hold space". To prepend a string literal to the pattern space, the <code>s</code> command can be used:
<syntaxhighlight lang="sed">s/^/String Literal/</syntaxhighlight>
To prepend a string literal to the hold space, it needs to be exchanged with the pattern space, before and after the operation:
<syntaxhighlight lang="sed">x
s/^/String Literal/
x</syntaxhighlight>
=={{header|Seed7}}==
<
const proc: main is func
Line 994 ⟶ 1,681:
s := "Hello " & s;
writeln(s);
end func;</
{{out}}
Line 1,002 ⟶ 1,689:
=={{header|Sidef}}==
<
str.sub!(/^/, 'He');
say str;</
or
<
str.prepend!('He');
say str;</
{{out}}
Line 1,015 ⟶ 1,702:
=={{header|SNOBOL4}}==
<
OUTPUT = s = 'Hello' s
END</
{{out}}
<pre>
Hello, World!
</pre>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "string_prepend" )
@( description, "Create a string variable equal to any text value." )
@( description, "" )
@( description, "Prepend the string variable with another string " )
@( description, "literal." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/String_prepend" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure string_prepend is
world : constant string := "World!";
hello : constant string := "Hello ";
s : string;
begin
-- Using concatenation
s := world;
s := hello & @;
? s;
-- Using strings library
s := world;
s := strings.insert( @, 1, hello );
? s;
command_line.set_exit_status( 0 );
end string_prepend;</syntaxhighlight>
{{out}}
<pre>
$ spar string_prepend.sp
Hello World!
Hello World!</pre>
=={{header|Standard ML}}==
<syntaxhighlight lang="text">
> val s="any text" ;
val s = "any text": string
> "prepended " ^ s;
val it = "prepended any text": string
</syntaxhighlight>
=={{header|Stata}}==
<
sca s="Ars Longa "+s
di s
Ars Longa Vita Brevis</
=={{header|Swift}}==
{{works with|Swift|5}}
<syntaxhighlight lang="swift">var str = ", World"
str = "Hello" + str
print(str)</syntaxhighlight>
{{out}}
<pre>
Hello, World!
</pre>
{{works with|Swift|1}}
<syntaxhighlight lang="swift">var str = ", World"
str = "Hello \(str)"
println(str)</
{{out}}
<pre>
Line 1,040 ⟶ 1,784:
=={{header|Tcl}}==
Concatenation is a fundamental feature of Tcl's basic language syntax.
<
set s "he$s"
puts $s</
{{out}}
<pre>hello world</pre>
=={{header|Ursa}}==
<
# set s to "world"
Line 1,056 ⟶ 1,800:
# outputs "hello world"
out s endl console</
=={{header|VBA}}==
<
Dim s As String
s = "bar"
s = "foo" & s
Debug.Print s
End Function</
=={{header|VBScript}}==
<
s = "foo" & s
WScript.Echo s</
{{Out}}
<pre>foobar</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">mut s := "world!"
s = "Hello, " + s
println(s)</syntaxhighlight>
{{out}}
<pre>
Hello, world!
</pre>
=={{header|Wart}}==
<
s <- ("0" + s)</
=={{header|Wren}}==
<syntaxhighlight lang="wren">var s = "world!"
s = "Hello, " + s
System.print(s)</syntaxhighlight>
{{out}}
<pre>
Hello, world!
</pre>
=={{header|Xojo}}==
<syntaxhighlight lang="vb">Dim s As String = "bar"
s = "foo" + s
MsgBox(s)</syntaxhighlight>
{{Out}}
<pre>foobar</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include xpllib;
char S, T(80);
[S:= "world!";
S:= StrCat(StrCopy(T,"Hello, "), S);
Text(0, S);
]</syntaxhighlight>
{{out}}
<pre>
Hello, world!
</pre>
=={{header|zkl}}==
<
s:="bar"; s=String("foo",s); s.println();
s:="bar"; s="%s%s".fmt("foo",s); s.println();
// a Data is a byte buffer/editor:
s:=Data(Void,"bar").insert(0,"foo").text; s.println();</
{{out}}
<pre>
|