String prepend: Difference between revisions
Alextretyak (talk | contribs) Added 11l |
Add ed example |
||
(33 intermediate revisions by 26 users not shown) | |||
Line 20: | Line 20: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">V s = ‘12345678’ |
||
s = ‘0’s |
s = ‘0’s |
||
print(s)</ |
print(s)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 30: | Line 30: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* String prepend - 14/04/2020 |
||
PREPEND CSECT |
PREPEND CSECT |
||
USING PREPEND,13 base register |
USING PREPEND,13 base register |
||
Line 47: | Line 47: | ||
B DC C'Hello ' b |
B DC C'Hello ' b |
||
C DC CL80' ' c |
C DC CL80' ' c |
||
END PREPEND</ |
END PREPEND</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 55: | Line 55: | ||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program appendstr64.s */ |
/* program appendstr64.s */ |
||
Line 170: | Line 170: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Output}} |
{{Output}} |
||
<pre> |
<pre> |
||
British Museum. |
British Museum. |
||
The rosetta stone is at 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> |
</pre> |
||
Line 181: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; |
||
procedure Prepend_String is |
procedure Prepend_String is |
||
Line 188: | Line 240: | ||
S := "Hello " & S;-- this is the operation to prepend "Hello " to S. |
S := "Hello " & S;-- this is the operation to prepend "Hello " to S. |
||
Ada.Text_IO.Put_Line(To_String(S)); |
Ada.Text_IO.Put_Line(To_String(S)); |
||
end Prepend_String;</ |
end Prepend_String;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 198: | Line 250: | ||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.7 algol68g-2.7].}} |
{{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).}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards).}} |
||
'''File: String_prepend.a68'''< |
'''File: String_prepend.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script # |
||
# -*- coding: utf-8 -*- # |
# -*- coding: utf-8 -*- # |
||
STRING str := "12345678"; |
STRING str := "12345678"; |
||
"0" +=: str; |
"0" +=: str; |
||
print(str)</ |
print(str)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 213: | Line 265: | ||
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: |
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 |
set aVariable to "Hello " & aVariable |
||
return aVariable</ |
return aVariable</syntaxhighlight> |
||
{{output}} |
{{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: |
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" |
use framework "Foundation" |
||
Line 238: | Line 290: | ||
set aVariable to aVariable's stringByReplacingOccurrencesOfString:("^") withString:("Hello ") ¬ |
set aVariable to aVariable's stringByReplacingOccurrencesOfString:("^") withString:("Hello ") ¬ |
||
options:(current application's NSRegularExpressionSearch) range:({0, 0}) |
options:(current application's NSRegularExpressionSearch) range:({0, 0}) |
||
-- return aVariable as text</ |
-- 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: |
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" |
use framework "Foundation" |
||
set aVariable to current application's class "NSMutableString"'s stringWithString:("world!") |
set aVariable to current application's class "NSMutableString"'s stringWithString:("world!") |
||
tell aVariable to insertString:("Hello ") atIndex:(0) |
tell aVariable to insertString:("Hello ") atIndex:(0) |
||
return aVariable as text</ |
return aVariable as text</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang="applescript">"Hello world!"</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">a: "World" |
||
a: "Hello" ++ a |
a: "Hello" ++ a |
||
print a |
print a |
||
Line 266: | Line 318: | ||
d: "World" |
d: "World" |
||
print prefix d "Hello"</ |
print prefix d "Hello"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 274: | Line 326: | ||
HelloWorld |
HelloWorld |
||
HelloWorld</pre> |
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}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">s := "foo" |
||
s := s "bar" |
s := s "bar" |
||
Msgbox % s</ |
Msgbox % s</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 285: | Line 344: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f STRING_PREPEND.AWK |
# syntax: GAWK -f STRING_PREPEND.AWK |
||
BEGIN { |
BEGIN { |
||
Line 293: | Line 352: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
foobar |
foobar |
||
</pre> |
</pre> |
||
=={{header|BaCon}}== |
|||
<syntaxhighlight lang="bacon">s$ = "prepend" |
|||
s$ = "String " & s$ |
|||
PRINT s$</syntaxhighlight> |
|||
{{out}} |
|||
<pre>String prepend</pre> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
< |
<syntaxhighlight lang="bbc basic">S$ = " World!" |
||
S$ = "Hello" + S$ |
S$ = "Hello" + S$ |
||
PRINT S$ |
PRINT S$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Hello World!</pre> |
<pre>Hello World!</pre> |
||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
< |
<syntaxhighlight lang="applesoft basic">100 LET S$=" World!" |
||
110 LET S$="Hello"+S$ |
110 LET S$="Hello"+S$ |
||
120 PRINT S$</ |
120 PRINT S$</syntaxhighlight> |
||
==={{header| |
==={{header|BASIC256}}=== |
||
<syntaxhighlight lang="basic256">a$ = " World!" |
|||
{{works with|BBC BASIC}} |
|||
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|GW-BASIC}}=== |
|||
{{works with|PC-BASIC|any}} |
|||
{{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}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 LET S$=" World!" |
||
110 LET S$="Hello"&S$ |
110 LET S$="Hello"&S$ |
||
120 PRINT 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}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat"> World!:?string |
||
& str$("Hello " !string):?string |
& str$("Hello " !string):?string |
||
& out$!string</ |
& out$!string</syntaxhighlight> |
||
<pre>Hello World!</pre> |
<pre>Hello World!</pre> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include<stdio.h> |
||
#include<string.h> |
#include<string.h> |
||
#include<stdlib.h> |
#include<stdlib.h> |
||
Line 340: | Line 492: | ||
printf("%s\n",str); |
printf("%s\n",str); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Changed my String</pre> |
<pre>Changed my String</pre> |
||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace PrependString |
namespace PrependString |
||
Line 359: | Line 511: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre>Hello World</pre> |
<pre>Hello World</pre> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">include <vector> |
||
#include <algorithm> |
#include <algorithm> |
||
#include <string> |
#include <string> |
||
Line 375: | Line 527: | ||
std::cout << prepended << std::endl ; |
std::cout << prepended << std::endl ; |
||
return 0 ; |
return 0 ; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>prepended tomy string</pre> |
<pre>prepended tomy string</pre> |
||
Line 382: | Line 534: | ||
===A pure function implementation with immutability === |
===A pure function implementation with immutability === |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn str-prepend [a-string, to-prepend] |
(defn str-prepend [a-string, to-prepend] |
||
(str to-prepend a-string)) |
(str to-prepend a-string)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== REPL demonstrations with mutability in mind === |
=== REPL demonstrations with mutability in mind === |
||
a) with the atom data structure |
a) with the atom data structure |
||
< |
<syntaxhighlight lang="clojure"> |
||
(def s (atom "World")) |
(def s (atom "World")) |
||
(swap! s #(str "Hello, " %)) |
(swap! s #(str "Hello, " %)) |
||
Line 396: | Line 548: | ||
user=> @s |
user=> @s |
||
user=> "Hello, Wolrd" |
user=> "Hello, Wolrd" |
||
</syntaxhighlight> |
|||
</lang> |
|||
b) with the ref data structure |
b) with the ref data structure |
||
< |
<syntaxhighlight lang="clojure"> |
||
(def s (ref "World")) |
(def s (ref "World")) |
||
(dosync (alter s #(str "Hello " %))) |
(dosync (alter s #(str "Hello " %))) |
||
Line 405: | Line 557: | ||
user=> @s |
user=> @s |
||
user=> "Hello World" |
user=> "Hello World" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> identification division. |
||
program-id. prepend. |
program-id. prepend. |
||
data division. |
data division. |
||
Line 432: | Line 584: | ||
move function reverse (str (1:len)) to str |
move function reverse (str (1:len)) to str |
||
. |
. |
||
end program prepend.</ |
end program prepend.</syntaxhighlight> |
||
<pre>Hello World!</pre> |
<pre>Hello World!</pre> |
||
{{works with|GNU Cobol|2.0}} |
{{works with|GNU Cobol|2.0}} |
||
< |
<syntaxhighlight lang="cobol"> >>SOURCE FREE |
||
PROGRAM-ID. prepend. |
PROGRAM-ID. prepend. |
||
Line 446: | Line 598: | ||
DISPLAY str |
DISPLAY str |
||
. |
. |
||
END PROGRAM prepend.</ |
END PROGRAM prepend.</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
=== Classic tag based CFML === |
=== Classic tag based CFML === |
||
< |
<syntaxhighlight lang="cfm"> |
||
<cfoutput> |
<cfoutput> |
||
<cfset who = "World!"> |
<cfset who = "World!"> |
||
#"Hello " & who# |
#"Hello " & who# |
||
</cfoutput> |
</cfoutput> |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Output}} |
{{Output}} |
||
<pre> |
<pre> |
||
Line 462: | Line 614: | ||
=== Script Based CFML === |
=== Script Based CFML === |
||
< |
<syntaxhighlight lang="cfm"><cfscript> |
||
who = "World!"; |
who = "World!"; |
||
greeting = "Hello " & who; |
greeting = "Hello " & who; |
||
writeOutput( greeting ); |
writeOutput( greeting ); |
||
</cfscript></ |
</cfscript></syntaxhighlight> |
||
{{Output}} |
{{Output}} |
||
<pre> |
<pre> |
||
Line 474: | Line 626: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
A macro is necessary in order to prepend a string in-place: |
A macro is necessary in order to prepend a string in-place: |
||
< |
<syntaxhighlight lang="lisp">(defmacro prependf (s &rest strs) |
||
"Prepend the given string variable with additional strings. The string variable is modified in-place." |
"Prepend the given string variable with additional strings. The string variable is modified in-place." |
||
`(setf ,s (concatenate 'string ,@strs ,s))) |
`(setf ,s (concatenate 'string ,@strs ,s))) |
||
Line 480: | Line 632: | ||
(defvar *str* "foo") |
(defvar *str* "foo") |
||
(prependf *str* "bar") |
(prependf *str* "bar") |
||
(format T "~a~%" *str*)</ |
(format T "~a~%" *str*)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>barfoo</pre> |
<pre>barfoo</pre> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
void main() { |
void main() { |
||
Line 491: | Line 643: | ||
s = "Hello " ~ s; |
s = "Hello " ~ s; |
||
writeln(s); |
writeln(s); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hello world!</pre> |
<pre>Hello world!</pre> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| System.SysUtils}} |
{{libheader| System.SysUtils}} |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program String_preappend; |
program String_preappend; |
||
Line 534: | Line 686: | ||
writeln(h); |
writeln(h); |
||
readln; |
readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hello World |
<pre>Hello World |
||
Line 542: | Line 694: | ||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">var s = "world!" |
||
s = "Hello " + s |
s = "Hello " + s |
||
print(s)</ |
print(s)</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">local :s "world!" |
||
set :s concat( "Hello " s) |
set :s concat( "Hello " s) |
||
!print s</ |
!print s</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hello world!</pre> |
<pre>Hello world!</pre> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="easylang"> |
|||
string$ = "Lang" |
|||
string$ = "Easy" & string$ |
|||
print string$ |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>EasyLang</pre> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
define-syntax-rule |
define-syntax-rule |
||
(set!-string-prepend a before) |
(set!-string-prepend a before) |
||
Line 565: | Line 726: | ||
name |
name |
||
→ "Elvis Presley" |
→ "Elvis Presley" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ed}}== |
|||
Port of [[#sed]] solution. |
|||
<syntaxhighlight lang="sed"> |
|||
s/^/String literal/ |
|||
</syntaxhighlight> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x: |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
import extensions'text; |
import extensions'text; |
||
Line 576: | Line 745: | ||
var s := "World"; |
var s := "World"; |
||
s := "Hello " + s; |
s := "Hello " + s; |
||
console.writeLine |
console.writeLine(s); |
||
// Alternative way |
// Alternative way |
||
var s2 := StringWriter.load("World"); |
var s2 := StringWriter.load("World"); |
||
s2.insert(0, "Hello "); |
s2.insert(0, "Hello "); |
||
console.writeLine |
console.writeLine(s2); |
||
console.readChar() |
console.readChar() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
<syntaxhighlight lang="elixir"> |
|||
<lang Elixir> |
|||
str1 = "World!" |
str1 = "World!" |
||
str = "Hello, " <> str1 |
str = "Hello, " <> str1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 595: | Line 764: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
===version 1=== |
|||
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: |
|||
<lang Emacs Lisp> |
|||
(defun glue (str1 str2) |
|||
<syntaxhighlight lang="lisp">(defvar str "bar") |
|||
(concat str1 str2) ) |
|||
(setq str (concat "foo" str)) |
|||
</lang> |
|||
str ;=> "foobar"</syntaxhighlight> |
|||
===version 2=== |
|||
<lang Emacs Lisp> |
|||
This can be hidden by using a macro such as <code>cl-callf2</code> which expands into the above code: |
|||
(defun glue (str1 str2) |
|||
(format "%s%s" str1 str2) ) |
|||
{{libheader|cl-lib}} |
|||
</lang> |
|||
<syntaxhighlight lang="lisp">(require 'cl-lib) |
|||
<b>Eval:</b> |
|||
<lang Emacs Lisp> |
|||
( |
(defvar str "bar") |
||
( |
(cl-callf2 concat "foo" str) |
||
str ;=> "foobar"</syntaxhighlight> |
|||
(insert str) |
|||
</lang> |
|||
Buffers can be thought of as expandable strings: |
|||
<b>Output:</b> |
|||
<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> |
<pre> |
||
hello world |
|||
Hello, World! |
|||
hello world |
|||
hello world |
|||
</pre> |
</pre> |
||
Line 626: | Line 817: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
...... |
...... |
||
S$=" World!" |
S$=" World!" |
||
Line 632: | Line 823: | ||
PRINT(S$) |
PRINT(S$) |
||
...... |
...... |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Hello World!</pre> |
<pre>Hello World!</pre> |
||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let mutable s = "world!" |
||
s <- "Hello, " + s |
s <- "Hello, " + s |
||
printfn "%s" s</ |
printfn "%s" s</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor"> |
||
"world" |
"world" |
||
"Hello " prepend |
"Hello " prepend |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
'''VBA/Python programmer's approach not sure if it's the most falconic way''' |
'''VBA/Python programmer's approach not sure if it's the most falconic way''' |
||
< |
<syntaxhighlight lang="falcon"> |
||
/* created by Aykayayciti Earl Lamont Montgomery |
/* created by Aykayayciti Earl Lamont Montgomery |
||
April 9th, 2018 */ |
April 9th, 2018 */ |
||
Line 657: | Line 848: | ||
s = s + "Falcon" |
s = s + "Falcon" |
||
> s |
> s |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 667: | Line 858: | ||
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. |
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. |
||
<lang>\ the following functions are commonly native to a Forth system. Shown for completeness |
<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 |
: C+! ( n addr -- ) dup c@ rot + swap c! ; \ primitive: increment a byte at addr by n |
||
Line 685: | Line 876: | ||
R> ; \ leave a copy of addr2 on the data stack |
R> ; \ leave a copy of addr2 on the data stack |
||
: writeln ( addr -- ) cr count type ; \ syntax sugar for testing</ |
: writeln ( addr -- ) cr count type ; \ syntax sugar for testing</syntaxhighlight> |
||
Test our language extensions interactively at the console |
Test our language extensions interactively at the console |
||
Line 701: | Line 892: | ||
===Initial difficulty=== |
===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:< |
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:<syntaxhighlight lang="fortran"> INTEGER*4 I,TEXT(66) |
||
DATA TEXT(1),TEXT(2),TEXT(3)/"Wo","rl","d!"/ |
DATA TEXT(1),TEXT(2),TEXT(3)/"Wo","rl","d!"/ |
||
Line 715: | Line 906: | ||
WRITE (6,3) (TEXT(I), I = 1,6) |
WRITE (6,3) (TEXT(I), I = 1,6) |
||
3 FORMAT (66A2) |
3 FORMAT (66A2) |
||
END</ |
END</syntaxhighlight> |
||
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". |
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 730: | Line 921: | ||
===Character facility=== |
===Character facility=== |
||
With F77 came the CHARACTER type... < |
With F77 came the CHARACTER type... <syntaxhighlight lang="fortran"> CHARACTER*66 TEXT |
||
TEXT = "World!" |
TEXT = "World!" |
||
TEXT = "Hello "//TEXT |
TEXT = "Hello "//TEXT |
||
WRITE (6,*) TEXT |
WRITE (6,*) TEXT |
||
END </ |
END </syntaxhighlight> |
||
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! |
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 741: | Line 932: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Var s = "prepend" |
Var s = "prepend" |
||
s = "String " + s |
s = "String " + s |
||
Print s |
Print s |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
String prepend |
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> |
</pre> |
||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=cd5ab867c22e872d69ed81fd9da96707 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=cd5ab867c22e872d69ed81fd9da96707 Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim sString1 As String = "world!" |
Dim sString1 As String = "world!" |
||
Dim sString2 As String = "Hello " |
Dim sString2 As String = "Hello " |
||
Line 763: | Line 986: | ||
Print sString1 |
Print sString1 |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 770: | Line 993: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">s := "world!" |
||
s = "Hello, " + s</ |
s = "Hello, " + s</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell"> |
||
Prelude> let f = (++" World!") |
Prelude> let f = (++" World!") |
||
Prelude> f "Hello" |
Prelude> f "Hello" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 784: | Line 1,007: | ||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="unicon">s := "world!" |
||
s := "Hello, " || s</ |
s := "Hello, " || s</syntaxhighlight> |
||
To demonstrate how this could be done with only one reference to the variable during the prepend: |
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 := ", world" |
||
s[1:1] ||:= "Hello" |
s[1:1] ||:= "Hello" |
||
write(s) |
write(s) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 801: | Line 1,024: | ||
Another take on it, using String Scanning: |
Another take on it, using String Scanning: |
||
< |
<syntaxhighlight lang="unicon">procedure main() |
||
(s := ", world") ?:= "Hello" || tab(0) |
(s := ", world") ?:= "Hello" || tab(0) |
||
write(s) |
write(s) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 811: | Line 1,034: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> s=: 'value' |
||
s |
s |
||
value |
value |
||
s=: 'new ',s |
s=: 'new ',s |
||
s |
s |
||
new value</ |
new value</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Java does not have a prepend method.<br /> |
|||
The most logical way to prepend a string value is with basic concatenation. |
|||
public class Prepend { |
|||
<syntaxhighlight lang="java"> |
|||
public static void main(String[] args) { |
|||
String string = "def"; |
|||
StringBuilder sb = new StringBuilder("world"); |
|||
string = "abc" + string; |
|||
sb.insert(0, "Hello, "); |
|||
</syntaxhighlight> |
|||
System.out.println(sb); |
|||
You could also use the ''String.concat'' method. |
|||
} |
|||
<syntaxhighlight lang="java"> |
|||
}</lang> |
|||
String string = "def"; |
|||
string = "abc".concat(string); |
|||
{{out}} |
|||
</syntaxhighlight> |
|||
<pre>prompt$ javac Prepend.java |
|||
You could use the ''StringBuilder'' class which provides an ''insert'' method. |
|||
prompt$ java Prepend |
|||
<syntaxhighlight lang="java"> |
|||
Hello, world</pre> |
|||
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}}== |
=={{header|Javascript}}== |
||
< |
<syntaxhighlight lang="javascript">// No built-in prepend |
||
var s=", World" |
var s=", World" |
||
s = "Hello" + s |
s = "Hello" + s |
||
print(s);</ |
print(s);</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
< |
<syntaxhighlight lang="jq">"world!" as $s |
||
| "Hello " + $s</ |
| "Hello " + $s</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">s = "world!" |
||
s = "Hello " * s</ |
s = "Hello " * s</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
s: "world!" |
s: "world!" |
||
"world!" |
"world!" |
||
"Hello " , s |
"Hello " , s |
||
"Hello world!" |
"Hello world!" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 868: | Line 1,108: | ||
t = t.prependIndent("Donald ") |
t = t.prependIndent("Donald ") |
||
println(t) |
println(t) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 877: | Line 1,117: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
{def str World} |
{def str World} |
||
-> str |
-> str |
||
Line 883: | Line 1,123: | ||
Hello, {str} |
Hello, {str} |
||
-> Hello, World |
-> Hello, World |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">local(x = ', World!') |
||
#x->merge(1,'Hello') |
#x->merge(1,'Hello') |
||
#x // Hello, World!</ |
#x // Hello, World!</syntaxhighlight> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
Line 894: | Line 1,134: | ||
Using the concatenation operator: |
Using the concatenation operator: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (set s "world") |
> (set s "world") |
||
"world" |
"world" |
||
> (++ "hello " s) |
> (++ "hello " s) |
||
"hello world" |
"hello world" |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using the concatenation function: |
Using the concatenation function: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (set s "world") |
> (set s "world") |
||
"world" |
"world" |
||
> (string:concat "hello " s) |
> (string:concat "hello " s) |
||
"hello world" |
"hello world" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">str = "world!" |
||
put "Hello " before str |
put "Hello " before str |
||
put str |
put str |
||
-- "Hello world!"</ |
-- "Hello world!"</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
The idiomatic way is to use "before"< |
The idiomatic way is to use "before"<syntaxhighlight lang="livecode">put "world" into x |
||
put "hello" before x |
put "hello" before x |
||
put x // hello world</ |
put x // hello world</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Line 925: | Line 1,165: | ||
By concatenation: |
By concatenation: |
||
< |
<syntaxhighlight lang="lua"> |
||
s = "12345678" |
s = "12345678" |
||
s = "0" .. s |
s = "0" .. s |
||
print(s)</ |
print(s)</syntaxhighlight> |
||
By string formatting: |
By string formatting: |
||
< |
<syntaxhighlight lang="lua"> |
||
s = "12345678" |
s = "12345678" |
||
s = string.format("%s%s", "0", s) |
s = string.format("%s%s", "0", s) |
||
print(s)</ |
print(s)</syntaxhighlight> |
||
By list joining: |
By list joining: |
||
< |
<syntaxhighlight lang="lua"> |
||
s = "12345678" |
s = "12345678" |
||
s = table.concat({"0", s}) |
s = table.concat({"0", s}) |
||
print(s)</ |
print(s)</syntaxhighlight> |
||
{{out}} of each solution: |
{{out}} of each solution: |
||
Line 950: | Line 1,190: | ||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module PrependString { |
Module PrependString { |
||
A$="Hello" |
A$="Hello" |
||
Line 957: | Line 1,197: | ||
} |
} |
||
PrependString |
PrependString |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 965: | Line 1,205: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">l := " World"; |
||
m := cat("Hello", l); |
m := cat("Hello", l); |
||
n := "Hello"||l; |
n := "Hello"||l; |
||
o := `||`("Hello", l);</ |
o := `||`("Hello", l);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 977: | Line 1,217: | ||
</pre> |
</pre> |
||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">a = "any text value"; |
||
a = "another string literal" <> a (* using concatenation (no built-in prepend) *)</ |
a = "another string literal" <> a (* using concatenation (no built-in prepend) *)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"another string literalany text value"</pre> |
<pre>"another string literalany text value"</pre> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury">:- module string_prepend. |
||
:- interface. |
:- interface. |
||
:- import_module io. |
:- import_module io. |
||
Line 992: | Line 1,232: | ||
main(!IO) :- |
main(!IO) :- |
||
S = "World!\n", |
S = "World!\n", |
||
io.write_string("Hello " ++ S, !IO).</ |
io.write_string("Hello " ++ S, !IO).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,000: | Line 1,240: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
Nanoquery has no idiomatic way to prepend one string to another. |
Nanoquery has no idiomatic way to prepend one string to another. |
||
< |
<syntaxhighlight lang="nanoquery">s1 = " a test" |
||
s1 = "this is" + s1 |
s1 = "this is" + s1 |
||
println s1</ |
println s1</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,011: | Line 1,251: | ||
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. |
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">/** |
|||
<lang ActionScript>/** |
|||
<doc><p>String prepend in Neko</pre></doc> |
<doc><p>String prepend in Neko</pre></doc> |
||
**/ |
**/ |
||
Line 1,017: | Line 1,257: | ||
var str = ", world" |
var str = ", world" |
||
str = "Hello" + str |
str = "Hello" + str |
||
$print(str, "\n")</ |
$print(str, "\n")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>prompt$ nekoc string-prepend.neko |
<pre>prompt$ nekoc string-prepend.neko |
||
Line 1,024: | Line 1,264: | ||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">s_ = 'world!' |
||
s_ = 'Hello, 's_ |
s_ = 'Hello, 's_ |
||
say s_</ |
say s_</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,033: | Line 1,273: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(setq str "bar") |
||
(push "foo" str) |
(push "foo" str) |
||
(println str)</ |
(println str)</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<lang |
<syntaxhighlight lang="nim"># Direct way. |
||
var str1, str2 = "12345678" |
|||
str = "0" & str |
|||
str1 = "0" & str1 |
|||
echo str</lang> |
|||
echo str1 |
|||
# Using "insert". |
|||
str2.insert("0") |
|||
echo str2 |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>012345678 |
|||
012345678</pre> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">class Prepend { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
s := "world!"; |
s := "world!"; |
||
"Hello {$s}"->PrintLine(); |
"Hello {$s}"->PrintLine(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,055: | Line 1,305: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let s = ", world" in |
let s = ", world" in |
||
let s = "Hello" ^ s in |
let s = "Hello" ^ s in |
||
print_endline s</ |
print_endline s</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">" World" "Hello" swap + println</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,071: | Line 1,321: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Not supported in GP. |
Not supported in GP. |
||
< |
<syntaxhighlight lang="parigp">s = "world!"; |
||
s = Str("Hello, ", s)</ |
s = Str("Hello, ", s)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>%1 = "Hello, world!"</pre> |
<pre>%1 = "Hello, world!"</pre> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
''See also [[#Free Pascal|Free Pascal]]'' |
|||
{{works with|Extended Pascal}} |
|||
<syntaxhighlight lang="pascal">program stringPrepend(output); |
|||
{{works with|Free Pascal|2.6.2}} |
|||
<lang Pascal>program StringPrepend; |
|||
{$mode objfpc}{$H+} |
|||
uses |
|||
{$IFDEF UNIX}{$IFDEF UseCThreads} |
|||
cthreads, |
|||
{$ENDIF}{$ENDIF} |
|||
Classes |
|||
{ you can add units after this }; |
|||
var |
var |
||
line: string(20); |
|||
s: String = ' World !'; |
|||
begin |
begin |
||
line := 'Hello '; |
|||
line := line + 'world!'; |
|||
WriteLn(S); |
|||
writeLn(line); |
|||
ReadLn; |
|||
end.</lang> |
|||
line := 'Hello '; |
|||
writeStr(line, line, 'world!'); |
|||
writeLn(line) |
|||
end.</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>Hello |
<pre>Hello world! |
||
Hello world!</pre> |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
var s := '12345678'; |
|||
s := '0' + s; |
|||
Print(s); |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
012345678 |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use warnings; |
use warnings; |
||
use feature ':all'; |
use feature ':all'; |
||
Line 1,121: | Line 1,380: | ||
$_ = 'bar'; |
$_ = 'bar'; |
||
$_ = "Foo$_"; |
$_ = "Foo$_"; |
||
say;</ |
say;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,131: | Line 1,390: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
<lang Phix>string s = "World" |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
s = "Hello "&s</lang> |
|||
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"World"</span> |
|||
<b>NB:</b> s = prepend(s,"Hello ") gives typecheck: s is {"Hello ",'W','o','r','l','d'}, rather than the "Hello World" you probably wanted. |
|||
<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>123456789 |
|||
A123456789 |
|||
BA123456789 |
|||
CBA123456789 |
|||
DECBA123456789</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(setq Str1 "12345678!") |
||
(setq Str1 (pack "0" Str1)) |
(setq Str1 (pack "0" Str1)) |
||
(println Str1)</ |
(println Str1)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,145: | Line 1,445: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
Pre_Cat: procedure options (main); /* 2 November 2013 */ |
Pre_Cat: procedure options (main); /* 2 November 2013 */ |
||
declare s character (100) varying; |
declare s character (100) varying; |
||
Line 1,152: | Line 1,452: | ||
put (s); |
put (s); |
||
end Pre_Cat; |
end Pre_Cat; |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
dust bowl |
dust bowl |
||
Line 1,158: | Line 1,458: | ||
=={{header|PlainTeX}}== |
=={{header|PlainTeX}}== |
||
< |
<syntaxhighlight lang="tex">\def\prepend#1#2{% #1=string #2=macro containing a string |
||
\def\tempstring{#1}% |
\def\tempstring{#1}% |
||
\expandafter\expandafter\expandafter |
\expandafter\expandafter\expandafter |
||
Line 1,168: | Line 1,468: | ||
\prepend{Hello }\mystring |
\prepend{Hello }\mystring |
||
Result : \mystring |
Result : \mystring |
||
\bye</ |
\bye</syntaxhighlight> |
||
Here is an equivalent code with eTeX capabilities: |
Here is an equivalent code with eTeX capabilities: |
||
< |
<syntaxhighlight lang="tex">\def\prepend#1#2{% #1=string #2=macro containing a string |
||
\edef#2{\unexpanded{#1}\unexpanded\expandafter{#2}}% |
\edef#2{\unexpanded{#1}\unexpanded\expandafter{#2}}% |
||
} |
} |
||
Line 1,177: | Line 1,477: | ||
\prepend{Hello }\mystring |
\prepend{Hello }\mystring |
||
Result : \mystring |
Result : \mystring |
||
\bye</ |
\bye</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
$str = "World!" |
$str = "World!" |
||
$str = "Hello, " + $str |
$str = "Hello, " + $str |
||
$str |
$str |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre>Hello, World!</pre> |
<pre>Hello, World!</pre> |
||
Line 1,199: | Line 1,499: | ||
the string. I define an operator for the purpose: |
the string. I define an operator for the purpose: |
||
< |
<syntaxhighlight lang="prolog"> |
||
:- op(200, xfx, user:(=+)). |
:- op(200, xfx, user:(=+)). |
||
Line 1,212: | Line 1,512: | ||
nb_setarg(2, Chars, Rest), |
nb_setarg(2, Chars, Rest), |
||
nb_setarg(1, Chars, X). |
nb_setarg(1, Chars, X). |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example of this abomination in action: |
Example of this abomination in action: |
||
< |
<syntaxhighlight lang="prolog"> |
||
?- Str = `World!`, `Hello, ` =+ Str. |
?- Str = `World!`, `Hello, ` =+ Str. |
||
Str = "Hello, World!".</ |
Str = "Hello, World!".</syntaxhighlight> |
||
Note: I can't imagine when I would want to do this in Prolog. |
Note: I can't imagine when I would want to do this in Prolog. |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">S$ = " World!" |
||
S$ = "Hello" + S$ |
S$ = "Hello" + S$ |
||
If OpenConsole() |
If OpenConsole() |
||
Line 1,230: | Line 1,530: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hello World!</pre> |
<pre>Hello World!</pre> |
||
Line 1,237: | Line 1,537: | ||
'''File: string_prepend.py''' |
'''File: string_prepend.py''' |
||
< |
<syntaxhighlight lang="python">#!/usr/bin/env python |
||
# -*- coding: utf-8 -*- |
# -*- coding: utf-8 -*- |
||
s = "12345678" |
s = "12345678" |
||
s = "0" + s # by concatenation |
s = "0" + s # by concatenation |
||
print(s)</ |
print(s)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,250: | Line 1,550: | ||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
< |
<syntaxhighlight lang="qbasic">s$ = "prepend" |
||
s$ = "String " + s$ |
s$ = "String " + s$ |
||
Print s$</ |
Print s$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>String prepend</pre> |
<pre>String prepend</pre> |
||
Line 1,258: | Line 1,558: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">$ "with a rubber duck." |
||
$ "One is never alone " |
$ "One is never alone " |
||
swap join |
swap join |
||
echo$</ |
echo$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,268: | Line 1,568: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">;there is no built-in way to set! prepend in racket |
||
(define str "foo") |
(define str "foo") |
||
(set! str (string-append "bar " str)) |
(set! str (string-append "bar " str)) |
||
Line 1,280: | Line 1,580: | ||
(set-prepend! macrostr "foo") |
(set-prepend! macrostr "foo") |
||
(displayln macrostr) |
(displayln macrostr) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>bar foo |
<pre>bar foo |
||
Line 1,287: | Line 1,587: | ||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line># explicit concatentation |
||
$_ = 'byte'; |
$_ = 'byte'; |
||
$_ = 'kilo' ~ $_; |
$_ = 'kilo' ~ $_; |
||
Line 1,310: | Line 1,610: | ||
$_ = 'cooper'; |
$_ = 'cooper'; |
||
$_ [R~]= 'mini'; |
$_ [R~]= 'mini'; |
||
.say;</ |
.say;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>kilobyte |
<pre>kilobyte |
||
Line 1,319: | Line 1,619: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">Red [] |
||
s: "world" |
s: "world" |
||
insert s "hello " |
insert s "hello " |
||
print s |
print s |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>hello world</pre> |
<pre>hello world</pre> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">zz= 'llo world!' /*─────────────── using literal abuttal.────────────*/ |
||
zz= 'he'zz /*This won't work if the variable name is X or B */ |
zz= 'he'zz /*This won't work if the variable name is X or B */ |
||
say zz |
say zz |
||
Line 1,341: | Line 1,641: | ||
bString= "he" |
bString= "he" |
||
aString= bString || aString |
aString= bString || aString |
||
say aString</ |
say aString</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre> |
<pre> |
||
Line 1,350: | Line 1,650: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
aString = "World!" |
aString = "World!" |
||
bString = "Hello, " + aString |
bString = "Hello, " + aString |
||
see bString + nl |
see bString + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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}}== |
=={{header|Ruby}}== |
||
There is a method for prepending a string, aptly named "prepend". |
There is a method for prepending a string, aptly named "prepend". |
||
< |
<syntaxhighlight lang="ruby">str = "llo world" |
||
str.prepend("He") |
str.prepend("He") |
||
p str #=> "Hello world"</ |
p str #=> "Hello world"</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust"> |
||
let mut s = "World".to_string(); |
let mut s = "World".to_string(); |
||
s.insert_str(0, "Hello "); |
s.insert_str(0, "Hello "); |
||
println!("{}", s); |
println!("{}", s); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Evaluation in Scala worksheet |
Evaluation in Scala worksheet |
||
< |
<syntaxhighlight lang="scala"> val s = "World" // Immutables are recommended //> s : String = World |
||
val f2 = () => ", " //Function assigned to variable |
val f2 = () => ", " //Function assigned to variable |
||
//> f2 : () => String = <function0> |
//> f2 : () => String = <function0> |
||
val s1 = "Hello" + f2() + s //> s1 : String = Hello, World |
val s1 = "Hello" + f2() + s //> s1 : String = Hello, World |
||
println(s1); //> Hello, World</ |
println(s1); //> Hello, World</syntaxhighlight> |
||
=={{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}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 1,386: | Line 1,702: | ||
s := "Hello " & s; |
s := "Hello " & s; |
||
writeln(s); |
writeln(s); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,394: | Line 1,710: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var str = 'llo!'; |
||
str.sub!(/^/, 'He'); |
str.sub!(/^/, 'He'); |
||
say str;</ |
say str;</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="ruby">var str = 'llo!'; |
||
str.prepend!('He'); |
str.prepend!('He'); |
||
say str;</ |
say str;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,407: | Line 1,723: | ||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol4"> s = ', World!' |
||
OUTPUT = s = 'Hello' s |
OUTPUT = s = 'Hello' s |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Hello, World! |
Hello, World! |
||
</pre> |
</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}}== |
=={{header|Standard ML}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
> val s="any text" ; |
> val s="any text" ; |
||
val s = "any text": string |
val s = "any text": string |
||
> "prepended " ^ s; |
> "prepended " ^ s; |
||
val it = "prepended any text": string |
val it = "prepended any text": string |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">sca s="Vita Brevis" |
||
sca s="Ars Longa "+s |
sca s="Ars Longa "+s |
||
di s |
di s |
||
Ars Longa Vita Brevis</ |
Ars Longa Vita Brevis</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
{{works with|Swift|5}} |
|||
<lang Swift>var str = ", World" |
|||
<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)" |
str = "Hello \(str)" |
||
println(str)</ |
println(str)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,441: | Line 1,805: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Concatenation is a fundamental feature of Tcl's basic language syntax. |
Concatenation is a fundamental feature of Tcl's basic language syntax. |
||
< |
<syntaxhighlight lang="tcl">set s "llo world" |
||
set s "he$s" |
set s "he$s" |
||
puts $s</ |
puts $s</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>hello world</pre> |
<pre>hello world</pre> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa">decl string s |
||
# set s to "world" |
# set s to "world" |
||
Line 1,457: | Line 1,821: | ||
# outputs "hello world" |
# outputs "hello world" |
||
out s endl console</ |
out s endl console</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Function StringPrepend() |
||
Dim s As String |
Dim s As String |
||
s = "bar" |
s = "bar" |
||
s = "foo" & s |
s = "foo" & s |
||
Debug.Print s |
Debug.Print s |
||
End Function</ |
End Function</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">s = "bar" |
||
s = "foo" & s |
s = "foo" & s |
||
WScript.Echo s</ |
WScript.Echo s</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>foobar</pre> |
<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}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="python">s <- "12345678" |
||
s <- ("0" + s)</ |
s <- ("0" + s)</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">var s = "world!" |
||
s = "Hello, " + s |
s = "Hello, " + s |
||
System.print(s)</ |
System.print(s)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,489: | Line 1,863: | ||
=={{header|Xojo}}== |
=={{header|Xojo}}== |
||
< |
<syntaxhighlight lang="vb">Dim s As String = "bar" |
||
s = "foo" + s |
s = "foo" + s |
||
MsgBox(s)</ |
MsgBox(s)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>foobar</pre> |
<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}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">s:="bar"; s="foo" + s; s.println(); |
||
s:="bar"; s=String("foo",s); s.println(); |
s:="bar"; s=String("foo",s); s.println(); |
||
s:="bar"; s="%s%s".fmt("foo",s); s.println(); |
s:="bar"; s="%s%s".fmt("foo",s); s.println(); |
||
// a Data is a byte buffer/editor: |
// a Data is a byte buffer/editor: |
||
s:=Data(Void,"bar").insert(0,"foo").text; s.println();</ |
s:=Data(Void,"bar").insert(0,"foo").text; s.println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 08:13, 4 July 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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
- Task
Create a string variable equal to any text value.
Prepend the string variable with another string literal.
If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions.
To illustrate the operation, show the content of the variable.
11l
V s = ‘12345678’
s = ‘0’s
print(s)
- Output:
012345678
360 Assembly
* 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
- Output:
Hello world!
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"
- Output:
British Museum. The rosetta stone is at British Museum.
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
- Output:
Screenshot from Atari 8-bit computer
Source "" at address $2A8A Prepend "World!" Result "World!" at address $2A8A Source "World!" at address $2A8A Prepend "Hello " Result "Hello World!" at address $2A8A
Ada
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.
with Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Prepend_String is
S: Unbounded_String := To_Unbounded_String("World!");
begin
S := "Hello " & S;-- this is the operation to prepend "Hello " to S.
Ada.Text_IO.Put_Line(To_String(S));
end Prepend_String;
- Output:
Hello World!
ALGOL 68
File: String_prepend.a68
#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
STRING str := "12345678";
"0" +=: str;
print(str)
- Output:
012345678
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:
set aVariable to "world!"
set aVariable to "Hello " & aVariable
return aVariable
- Output:
"Hello world!"
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:
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
But there's also an NSMutableString class. This has 'replace' versions of the 'stringByReplacing' methods above and also this insertString:atIndex: method:
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
- Output:
"Hello world!"
Arturo
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"
- Output:
HelloWorld HelloWorld HelloWorld HelloWorld
Asymptote
string s1 = " World!";
write("Hello" + s1);
write("Hello", s1);
string s2 = "Hello" + s1;
write(s2);
AutoHotkey
s := "foo"
s := s "bar"
Msgbox % s
- Output:
foobar
AWK
# syntax: GAWK -f STRING_PREPEND.AWK
BEGIN {
s = "bar"
s = "foo" s
print(s)
exit(0)
}
- Output:
foobar
BaCon
s$ = "prepend"
s$ = "String " & s$
PRINT s$
- Output:
String prepend
BASIC
S$ = " World!"
S$ = "Hello" + S$
PRINT S$
- Output:
Hello World!
Applesoft BASIC
100 LET S$=" World!"
110 LET S$="Hello"+S$
120 PRINT S$
BASIC256
a$ = " World!"
a$ = "Hello"; a$
print a$
# would also be valid
a$ = "Hello" + a$
# and
a$ = "Hello" & a$
Chipmunk Basic
10 A$ = " World!"
20 A$ = "Hello" + A$
30 PRINT A$
GW-BASIC
10 A$ = " World!"
20 A$ = "Hello" + A$
30 PRINT A$
IS-BASIC
100 LET S$=" World!"
110 LET S$="Hello"&S$
120 PRINT S$
MSX Basic
10 A$ = " World!"
20 A$ = "Hello" + A$
30 PRINT A$
Run BASIC
a$ = " World!"
a$ = "Hello" + a$
print a$
' en RB, LB and BASIC256 would also be valid
a$ = "Hello"; a$
Quite BASIC
10 LET A$ = " World!"
20 LET A$ = "Hello" + A$
30 PRINT A$
True BASIC
LET a$ = " World!"
LET a$ = "Hello" & a$
PRINT a$
END
Yabasic
a$ = " World!"
a$ = "Hello" + a$
print a$
Binary Lambda Calculus
BLC program
18 16 46 80 05 bc bc fd f6 e0 67 6d 61
based on https://github.com/tromp/AIT/blob/master/rosetta/catstrings.lam prepends "ma" to "gma" to output "magma".
Bracmat
World!:?string
& str$("Hello " !string):?string
& out$!string
Hello World!
C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[100]="my String";
char *cstr="Changed ";
char *dup;
sprintf(str,"%s%s",cstr,(dup=strdup(str)));
free(dup);
printf("%s\n",str);
return 0;
}
- Output:
Changed my String
C#
using System;
namespace PrependString
{
class Program
{
static void Main(string[] args)
{
string str = "World";
str = "Hello " + str;
Console.WriteLine(str);
Console.ReadKey();
}
}
}
Hello World
C++
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 ;
}
- Output:
prepended tomy string
Clojure
A pure function implementation with immutability
(defn str-prepend [a-string, to-prepend]
(str to-prepend a-string))
REPL demonstrations with mutability in mind
a) with the atom data structure
(def s (atom "World"))
(swap! s #(str "Hello, " %))
user=> @s
user=> "Hello, Wolrd"
b) with the ref data structure
(def s (ref "World"))
(dosync (alter s #(str "Hello " %)))
user=> @s
user=> "Hello World"
COBOL
identification division.
program-id. prepend.
data division.
working-storage section.
1 str pic x(30) value "World!".
1 binary.
2 len pic 9(4) value 0.
2 scratch pic 9(4) value 0.
procedure division.
begin.
perform rev-sub-str
move function reverse ("Hello ") to str (len + 1:)
perform rev-sub-str
display str
stop run
.
rev-sub-str.
move 0 to len scratch
inspect function reverse (str)
tallying scratch for leading spaces
len for characters after space
move function reverse (str (1:len)) to str
.
end program prepend.
Hello World!
>>SOURCE FREE
PROGRAM-ID. prepend.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 str PIC X(30) VALUE "world!".
PROCEDURE DIVISION.
MOVE FUNCTION CONCATENATE("Hello, ", str) TO str
DISPLAY str
.
END PROGRAM prepend.
ColdFusion
Classic tag based CFML
<cfoutput>
<cfset who = "World!">
#"Hello " & who#
</cfoutput>
- Output:
Hello World!
Script Based CFML
<cfscript>
who = "World!";
greeting = "Hello " & who;
writeOutput( greeting );
</cfscript>
- Output:
Hello World!
Common Lisp
A macro is necessary in order to prepend a string in-place:
(defmacro prependf (s &rest strs)
"Prepend the given string variable with additional strings. The string variable is modified in-place."
`(setf ,s (concatenate 'string ,@strs ,s)))
(defvar *str* "foo")
(prependf *str* "bar")
(format T "~a~%" *str*)
- Output:
barfoo
D
import std.stdio;
void main() {
string s = "world!";
s = "Hello " ~ s;
writeln(s);
}
- Output:
Hello world!
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.
- Output:
Hello World Hello World Hello World
Dyalect
var s = "world!"
s = "Hello " + s
print(s)
Déjà Vu
local :s "world!"
set :s concat( "Hello " s)
!print s
- Output:
Hello world!
EasyLang
string$ = "Lang"
string$ = "Easy" & string$
print string$
- Output:
EasyLang
EchoLisp
define-syntax-rule
(set!-string-prepend a before)
(set! a (string-append before a)))
→ #syntax:set!-string-prepend
(define name "Presley")
→ name
(set!-string-prepend name "Elvis ")
name
→ "Elvis Presley"
ed
Port of #sed solution.
s/^/String literal/
Elena
ELENA 6.x:
import extensions;
import extensions'text;
public program()
{
var s := "World";
s := "Hello " + s;
console.writeLine(s);
// Alternative way
var s2 := StringWriter.load("World");
s2.insert(0, "Hello ");
console.writeLine(s2);
console.readChar()
}
Elixir
str1 = "World!"
str = "Hello, " <> str1
- Output:
"Hello, World!"
Emacs Lisp
While strings in Emacs Lisp are mutable, they're fixed size. Therefore the concat
function creates a new string and the existing string must be referenced twice:
(defvar str "bar")
(setq str (concat "foo" str))
str ;=> "foobar"
This can be hidden by using a macro such as cl-callf2
which expands into the above code:
(require 'cl-lib)
(defvar str "bar")
(cl-callf2 concat "foo" str)
str ;=> "foobar"
Buffers can be thought of as expandable strings:
(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"
EMal
text greeting = "world"
^|basic concatenation|^
writeLine("hello " + greeting)
^|changing the text in place|^
writeLine(greeting.insert(0, "hello "))
writeLine(greeting)
- Output:
hello world hello world hello world
Erlang
- Output:
1> S = "world". "world" 2> "Hello " ++ S. "Hello world"
ERRE
......
S$=" World!"
S$="Hello"+S$
PRINT(S$)
......
- Output:
Hello World!
F#
let mutable s = "world!"
s <- "Hello, " + s
printfn "%s" s
Factor
"world"
"Hello " prepend
Falcon
VBA/Python programmer's approach not sure if it's the most falconic way
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
s = "fun "
s = s + "Falcon"
> s
- Output:
fun Falcon [Finished in 0.2s]
Forth
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.
\ 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
: +PLACE ( addr1 length addr2 -- ) \ Append addr1 length to addr2
2dup 2>r count + swap move 2r> c+! ;
: PLACE ( addr1 len addr2 -- ) \ addr1 and length, placed at addr2 as counted string
2dup 2>r 1+ swap move 2r> c! ;
\ Example begins here
: PREPEND ( addr len addr2 -- addr2)
>R \ push addr2 to return stack
PAD PLACE \ place the 1st string in PAD
R@ count PAD +PLACE \ append PAD with addr2 string
PAD count R@ PLACE \ move the whole thing back into addr2
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
256 buffer: string1 ok s" needs no introduction!" string1 place ok string1 writeln needs no introduction! ok s" This string " string1 prepend writeln This string needs no introduction! ok
Fortran
Early inability
Early Fortran had almost no ability to manipulate text except via overwriting text literals in a FORMAT statement used in a READ, that would then appear when the same FORMAT statement was used in a WRITE (!) perhaps as a heading.
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:
INTEGER*4 I,TEXT(66)
DATA TEXT(1),TEXT(2),TEXT(3)/"Wo","rl","d!"/
WRITE (6,1) (TEXT(I), I = 1,3)
1 FORMAT ("Hello ",66A2)
DO 2 I = 1,3
2 TEXT(I + 3) = TEXT(I)
TEXT(1) = "He"
TEXT(2) = "ll"
TEXT(3) = "o "
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: "Wo"
is deemed to be "Wo "
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".
The first output (to standard output: unit 6) thus prepends the text "Hello " via the workings of the nominated FORMAT statement without a further mention of variable TEXT, itself not being modified in this action. Thus, this is an example of a single-mention possibility.
Some versions of Fortran offered the ability to write to a variable such as an array rather than to a nominated output unit, via a statement like WRITE (TEXT,1) (TEXT(I),I = 1,3)
, which array could then itself be written to the actual output via normal statements. This would involve a working variable within the routines for formatted I/O to hold the output, and thus provides one of the reasons that Fortran I/O implementations seldom enable re-entrancy - as with a WRITE statement whose output expression list includes a function evaluation, which function itself attempts to WRITE something, say to a log file, with both WRITE statements employing formatting statements. More modern compilers now require the recipient for this sort of WRITE statement to be of type CHARACTER, so the older style is blocked - and re-entrancy is still a problem.
Still another variant involved writing to unit number zero, which did not actually send anything to an output recipient. Instead, the scratchpad used by the formatted I/O system would retain whatever was produced, which could then be read back via unit number zero. Indeed, reading from unit zero would reveal whatever had been the last line of the previous I/O statement. This would be of interest if a format error had been reported on a READ during some mass data acquisition, so that the error message could show the problematic input that had been obtained rather than just complain. But this facility was not common, and did not become a part of the F90 standard. Perhaps a BACKSPACE and re-read to a text variable will work instead...
Retreating from FORMAT usage to the case of manipulating a "string" variable so as to prepend a given text to the working variable, first the existing content must be moved right to make room (again, an even number of characters is involved) which is achieved via the DO-loop, using certain constants. If on the other hand, text were to be removed from the front, then a loop would be needed to shift the surviving content leftwards. In doing this, one must pay attention to any overlaps and the direction of the loop! By chance, this exercise starts the placement after the end of the existing text but if instead the shift were to be two units, then the first-placed unit would land atop the tail end of the existing text. Thus, for rightwards shifts, one should start with the end of the surviving text and work back to its start.
Having made space, the next statements merely assign some bit patterns to elements of TEXT, and then the result is revealed, again using known constants instead of the associated variables of the more general approach. The result from the two WRITE statements is of course
Hello world! Hello world!
Character facility
With F77 came the CHARACTER type...
CHARACTER*66 TEXT
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, TEXT(1:6) = "World!"
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!
Modern
With F90, and standardised in F2003, came extensions that enable a variable to be "cut-to-fit" on each usage. The first assignment would discard any storage associated with TEXT and re-assign space matching the size of the expression's result, so TEXT would have six characters. In the next statement, the expression would be evaluated and produce twelve characters (six from "Hello ", and the six of the current size of TEXT), then the current storage for text would be discarded and TEXT re-allocated to be of size twelve. At some cost in overhead. On the other hand, rather than copy the result of an expression from the scratchpad to the recipient, with re-allocation, the recipient variable could be repointed to the result area: no copying needed.
FreeBASIC
' FB 1.05.0 Win64
Var s = "prepend"
s = "String " + s
Print s
Sleep
- Output:
String prepend
Free Pascal
Free Pascal supports everything shown in § Pascal (except the string schema data type, string(20) must be written like here). Furthermore, using the compiler directive {$COperators} the following is possible, too:
var
line: string[20];
begin
line := 'Hello ';
{$COperators on}
line += 'world!';
writeLn(line)
end.
FutureBasic
include "NSLog.incl"
void local fn DoIt
CFStringRef s = @"world!"
s = fn StringByAppendingString( @"Hello ", s )
NSLog(@"%@",s)
end fn
fn DoIt
HandleEvents
- Output:
Hello world!
Gambas
Click this link to run this code
Public Sub Main()
Dim sString1 As String = "world!"
Dim sString2 As String = "Hello "
sString1 = sString2 & sString1
Print sString1
End
Output:
Hello world!
Go
s := "world!"
s = "Hello, " + s
Haskell
Prelude> let f = (++" World!")
Prelude> f "Hello"
- Output:
"Hello world!"
Icon and Unicon
s := "world!"
s := "Hello, " || s
To demonstrate how this could be done with only one reference to the variable during the prepend:
procedure main()
s := ", world"
s[1:1] ||:= "Hello"
write(s)
end
- Output:
prompt$ unicon -s prepend.icn -x Hello, world
Another take on it, using String Scanning:
procedure main()
(s := ", world") ?:= "Hello" || tab(0)
write(s)
end
- Output:
prompt$ unicon -s prepend.icn -x Hello, world
J
s=: 'value'
s
value
s=: 'new ',s
s
new value
Java
Java does not have a prepend method.
The most logical way to prepend a string value is with basic concatenation.
String string = "def";
string = "abc" + string;
You could also use the String.concat method.
String string = "def";
string = "abc".concat(string);
You could use the StringBuilder class which provides an insert method.
StringBuilder string = new StringBuilder();
string.append("def");
string.insert(0, "abc");
Additionally, you could use the String.format or String.formatted methods.
String string = "def";
string = String.format("abc%s", string);
String string = "def";
string = "abc%s".formatted(string);
All of these will produce the following output.
abcdef
JavaScript
// No built-in prepend
var s=", World"
s = "Hello" + s
print(s);
jq
"world!" as $s
| "Hello " + $s
Julia
s = "world!"
s = "Hello " * s
K
s: "world!"
"world!"
"Hello " , s
"Hello world!"
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
var s = "Obama"
s = "Barack " + s
println(s)
// It's also possible to use this standard library function
// though this is not what it's really intended for
var t = "Trump"
t = t.prependIndent("Donald ")
println(t)
}
- Output:
Barack Obama Donald Trump
Lambdatalk
{def str World}
-> str
Hello, {str}
-> Hello, World
Lasso
local(x = ', World!')
#x->merge(1,'Hello')
#x // Hello, World!
LFE
Using the concatenation operator:
> (set s "world")
"world"
> (++ "hello " s)
"hello world"
Using the concatenation function:
> (set s "world")
"world"
> (string:concat "hello " s)
"hello world"
Lingo
str = "world!"
put "Hello " before str
put str
-- "Hello world!"
LiveCode
The idiomatic way is to use "before"
put "world" into x
put "hello" before x
put x // hello world
Lua
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)
- Output:
of each solution
012345678
M2000 Interpreter
Module PrependString {
A$="Hello"
A$+=" World"
Print A$
}
PrependString
- Output:
Hello World
Maple
l := " World";
m := cat("Hello", l);
n := "Hello"||l;
o := `||`("Hello", l);
- Output:
" World" "Hello World" "Hello World" "Hello World"
Mathematica /Wolfram Language
a = "any text value";
a = "another string literal" <> a (* using concatenation (no built-in prepend) *)
- Output:
"another string literalany text value"
Mercury
:- module string_prepend.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module string.
main(!IO) :-
S = "World!\n",
io.write_string("Hello " ++ S, !IO).
- Output:
Hello World!
Nanoquery
Nanoquery has no idiomatic way to prepend one string to another.
s1 = " a test"
s1 = "this is" + s1
println s1
- Output:
this is a test
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.
/**
<doc><p>String prepend in Neko</pre></doc>
**/
var str = ", world"
str = "Hello" + str
$print(str, "\n")
- Output:
prompt$ nekoc string-prepend.neko prompt$ neko string-prepend.n Hello, world
NetRexx
s_ = 'world!'
s_ = 'Hello, 's_
say s_
- Output:
Hello, world!
NewLISP
(setq str "bar")
(push "foo" str)
(println str)
Nim
# Direct way.
var str1, str2 = "12345678"
str1 = "0" & str1
echo str1
# Using "insert".
str2.insert("0")
echo str2
- Output:
012345678 012345678
Objeck
class Prepend {
function : Main(args : String[]) ~ Nil {
s := "world!";
"Hello {$s}"->PrintLine();
}
}
Hello World!
OCaml
let () =
let s = ", world" in
let s = "Hello" ^ s in
print_endline s
Oforth
" World" "Hello" swap + println
- Output:
Hello World
PARI/GP
Not supported in GP.
s = "world!";
s = Str("Hello, ", s)
- Output:
%1 = "Hello, world!"
Pascal
See also Free Pascal
program stringPrepend(output);
var
line: string(20);
begin
line := 'Hello ';
line := line + 'world!';
writeLn(line);
line := 'Hello ';
writeStr(line, line, 'world!');
writeLn(line)
end.
- Output:
Hello world! Hello world!
PascalABC.NET
##
var s := '12345678';
s := '0' + s;
Print(s);
- Output:
012345678
Perl
use strict;
use warnings;
use feature ':all';
# explicit concatentation
$_ = 'bar';
$_ = 'Foo' . $_;
say;
# lvalue substr
$_ = 'bar';
substr $_, 0, 0, 'Foo';
say;
# interpolation as concatenation
# (NOT safe if concatenate sigils)
$_ = 'bar';
$_ = "Foo$_";
say;
- Output:
Foobar Foobar Foobar
Phix
string s = "World" s = "Hello "&s
NB: 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.
- 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).
Phixmonti
/# Rosetta Code problem: https://rosettacode.org/wiki/String_prepend
by Galileo, 10/2022 #/
"Hello " var s
s "world" chain var s
s print
Picat
As usual there are a couple ways of doing this. The most common is probable to use string concatenation (++
), but append/3
might be useful if backtracking is needed.
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.
- Output:
123456789 A123456789 BA123456789 CBA123456789 DECBA123456789
PicoLisp
(setq Str1 "12345678!")
(setq Str1 (pack "0" Str1))
(println Str1)
- Output:
"012345678!"
PL/I
Pre_Cat: procedure options (main); /* 2 November 2013 */
declare s character (100) varying;
s = ' bowl';
s = 'dust' || s;
put (s);
end Pre_Cat;
dust bowl
Plain TeX
\def\prepend#1#2{% #1=string #2=macro containing a string
\def\tempstring{#1}%
\expandafter\expandafter\expandafter
\def\expandafter\expandafter\expandafter
#2\expandafter\expandafter\expandafter
{\expandafter\tempstring#2}%
}
\def\mystring{world!}
\prepend{Hello }\mystring
Result : \mystring
\bye
Here is an equivalent code with eTeX capabilities:
\def\prepend#1#2{% #1=string #2=macro containing a string
\edef#2{\unexpanded{#1}\unexpanded\expandafter{#2}}%
}
\def\mystring{world!}
\prepend{Hello }\mystring
Result : \mystring
\bye
PowerShell
$str = "World!"
$str = "Hello, " + $str
$str
Hello, World!
Prolog
In its admirable wisdom, Prolog is generally unfriendly to state mutations and destructive assignment. However, it is also very flexible. Using the traditional representation of strings as lists of character codes, and the non-logical predicate `setarg/3`, we can destructively set the head and tail of the list to achieve a mutation of the variable holding the string. I define an operator for the purpose:
:- op(200, xfx, user:(=+)).
%% +Prepend =+ +Chars
%
% Will destructively update Chars
% So that Chars = Prepend prefixed to Chars.
% eazar001 in ##prolog helped refine this approach.
[X|Xs] =+ Chars :-
append(Xs, Chars, Rest),
nb_setarg(2, Chars, Rest),
nb_setarg(1, Chars, X).
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.
PureBasic
S$ = " World!"
S$ = "Hello" + S$
If OpenConsole()
PrintN(S$)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
- Output:
Hello World!
Python
File: string_prepend.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = "12345678"
s = "0" + s # by concatenation
print(s)
- Output:
012345678
QB64
s$ = "prepend"
s$ = "String " + s$
Print s$
- Output:
String prepend
Quackery
$ "with a rubber duck."
$ "One is never alone "
swap join
echo$
- Output:
One is never alone with a rubber duck.
Racket
;there is no built-in way to set! prepend in racket
(define str "foo")
(set! str (string-append "bar " str))
(displayln str)
;but you can create a quick macro to solve that problem
(define-syntax-rule (set-prepend! str value)
(set! str (string-append value str)))
(define macrostr " bar")
(set-prepend! macrostr "foo")
(displayln macrostr)
- Output:
bar foo foo bar
Raku
(formerly Perl 6)
# 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;
- Output:
kilobyte megabuck nanobit microfortnight minicooper
Red
Red []
s: "world"
insert s "hello "
print s
- Output:
hello world
REXX
zz= 'llo world!' /*─────────────── using literal abuttal.────────────*/
zz= 'he'zz /*This won't work if the variable name is X or B */
say zz
gg = "llo world!" /*─────────────── using literal concatenation.──────*/
gg = 'he' || gg
say gg
aString= 'llo world!' /*─────────────── using variable concatenation.─────*/
bString= "he"
aString= bString || aString
say aString
output
hello world! hello world! hello world!
Ring
aString = "World!"
bString = "Hello, " + aString
see bString + nl
RPL
In HP-48+ RPL versions, the STO+
instruction can either append or prepend a string to a variable containing already a string.
"def" 'Z' STO "abc" 'Z' STO+ Z
Output
1: "abcdef"
Ruby
There is a method for prepending a string, aptly named "prepend".
str = "llo world"
str.prepend("He")
p str #=> "Hello world"
Rust
let mut s = "World".to_string();
s.insert_str(0, "Hello ");
println!("{}", s);
Scala
Evaluation in Scala worksheet
val s = "World" // Immutables are recommended //> s : String = World
val f2 = () => ", " //Function assigned to variable
//> f2 : () => String = <function0>
val s1 = "Hello" + f2() + s //> s1 : String = Hello, World
println(s1); //> Hello, World
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 s
command can be used:
s/^/String Literal/
To prepend a string literal to the hold space, it needs to be exchanged with the pattern space, before and after the operation:
x
s/^/String Literal/
x
Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var string: s is "world!";
begin
s := "Hello " & s;
writeln(s);
end func;
- Output:
Hello world!
Sidef
var str = 'llo!';
str.sub!(/^/, 'He');
say str;
or
var str = 'llo!';
str.prepend!('He');
say str;
- Output:
Hello!
SNOBOL4
s = ', World!'
OUTPUT = s = 'Hello' s
END
- Output:
Hello, World!
SparForte
As a structured script.
#!/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;
- Output:
$ spar string_prepend.sp Hello World! Hello World!
Standard ML
> val s="any text" ;
val s = "any text": string
> "prepended " ^ s;
val it = "prepended any text": string
Stata
sca s="Vita Brevis"
sca s="Ars Longa "+s
di s
Ars Longa Vita Brevis
Swift
var str = ", World"
str = "Hello" + str
print(str)
- Output:
Hello, World!
var str = ", World"
str = "Hello \(str)"
println(str)
- Output:
Hello, World!
Tcl
Concatenation is a fundamental feature of Tcl's basic language syntax.
set s "llo world"
set s "he$s"
puts $s
- Output:
hello world
Ursa
decl string s
# set s to "world"
set s "world"
# prepend "hello "
set s (+ "hello " s)
# outputs "hello world"
out s endl console
VBA
Function StringPrepend()
Dim s As String
s = "bar"
s = "foo" & s
Debug.Print s
End Function
VBScript
s = "bar"
s = "foo" & s
WScript.Echo s
- Output:
foobar
V (Vlang)
mut s := "world!"
s = "Hello, " + s
println(s)
- Output:
Hello, world!
Wart
s <- "12345678"
s <- ("0" + s)
Wren
var s = "world!"
s = "Hello, " + s
System.print(s)
- Output:
Hello, world!
Xojo
Dim s As String = "bar"
s = "foo" + s
MsgBox(s)
- Output:
foobar
XPL0
include xpllib;
char S, T(80);
[S:= "world!";
S:= StrCat(StrCopy(T,"Hello, "), S);
Text(0, S);
]
- Output:
Hello, world!
zkl
s:="bar"; s="foo" + s; s.println();
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();
- Output:
foobar foobar foobar foobar
- Programming Tasks
- Basic language learning
- Basic Data Operations
- String manipulation
- Simple
- Bc/Omit
- Dc/Omit
- 11l
- 360 Assembly
- AArch64 Assembly
- Action!
- Ada
- ALGOL 68
- AppleScript
- Arturo
- Asymptote
- AutoHotkey
- AWK
- BaCon
- BASIC
- Applesoft BASIC
- BASIC256
- Chipmunk Basic
- GW-BASIC
- IS-BASIC
- MSX Basic
- Run BASIC
- Quite BASIC
- True BASIC
- Yabasic
- Binary Lambda Calculus
- Bracmat
- C
- C sharp
- C++
- Clojure
- COBOL
- ColdFusion
- Common Lisp
- D
- Delphi
- System.SysUtils
- Dyalect
- Déjà Vu
- EasyLang
- EchoLisp
- Ed
- Elena
- Elixir
- Emacs Lisp
- Cl-lib
- EMal
- Erlang
- ERRE
- F Sharp
- Factor
- Falcon
- Forth
- Fortran
- FreeBASIC
- Free Pascal
- FutureBasic
- Gambas
- Go
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- K
- Kotlin
- Lambdatalk
- Lasso
- LFE
- Lingo
- LiveCode
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- Mercury
- Nanoquery
- Neko
- NetRexx
- NewLISP
- Nim
- Objeck
- OCaml
- Oforth
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- Phixmonti
- Picat
- PicoLisp
- PL/I
- PlainTeX
- PowerShell
- Prolog
- PureBasic
- Python
- QB64
- Quackery
- Racket
- Raku
- Red
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Sed
- Seed7
- Sidef
- SNOBOL4
- SparForte
- Standard ML
- Stata
- Swift
- Tcl
- Ursa
- VBA
- VBScript
- V (Vlang)
- Wart
- Wren
- Xojo
- XPL0
- Zkl
- Pages with too many expensive parser function calls