String prepend: Difference between revisions
m (→{{header|Python}}: Coding style (no semi-colons, no hash at end of comment), do not overwrite 'str' builtin, spelling, filename case) |
(Add three Lua solutions) |
||
Line 224: | Line 224: | ||
#x // Hello, World!</lang> |
#x // Hello, World!</lang> |
||
=={{header|Lua}}== |
|||
By concatenation: |
|||
<lang lua> |
|||
s = "12345678" |
|||
s = "0" .. s |
|||
print(s)</lang> |
|||
By string formatting: |
|||
<lang lua> |
|||
s = "12345678" |
|||
s = string.format("%s%s", "0", s) |
|||
print(s)</lang> |
|||
By list joining: |
|||
<lang lua> |
|||
s = "12345678" |
|||
s = table.concat({"0", s}) |
|||
print(s)</lang> |
|||
'''Output''' of each solution: |
|||
012345678 |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}== |
||
Line 230: | Line 256: | ||
{{out}} |
{{out}} |
||
<pre>"another string literalany text value"</pre> |
<pre>"another string literalany text value"</pre> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
Revision as of 22:39, 30 September 2014
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
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.
ALGOL 68
File: String_prepend.a68<lang algol68>#!/usr/bin/a68g --script #
- -*- coding: utf-8 -*- #
STRING str := "12345678"; "0" +=: str; print(str)</lang>Output:
012345678
AutoHotkey
<lang autohotkey>s := "foo" s := s "bar" Msgbox % s</lang> output:
foobar
AWK
<lang AWK>
- syntax: GAWK -f STRING_PREPEND.AWK
BEGIN {
s = "bar" s = "foo" s print(s) exit(0)
} </lang>
output:
foobar
BASIC
<lang BBC BASIC>S$ = " World!" S$ = "Hello" + S$ PRINT S$ </lang>
- Output:
Hello World!
Applesoft BASIC
BBC BASIC
Bracmat
<lang bracmat> World!:?string & str$("Hello " !string):?string & out$!string</lang>
Hello World!
C
<lang 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;
}</lang>
- Output:
Changed my String
C++
<lang cpp>include <vector>
- include <algorithm>
- include <string>
- include <iostream>
int main( ) {
std::vector<std::string> myStrings { "prepended to" , "my string" } ; std::string prepended = std::accumulate( myStrings.begin( ) ,
myStrings.end( ) , std::string( "" ) , []( std::string a , std::string b ) { return a + b ; } ) ;
std::cout << prepended << std::endl ; return 0 ;
}</lang>
- Output:
prepended tomy string
Clojure
<lang clojure>(def s (ref "World")) (dosync (alter s #(str "Hello " %)))
user=> @s "Hello World"</lang>
COBOL
<lang cobol> >>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.</lang>
Common Lisp
A macro is necessary in order to prepend a string in-place: <lang lisp>(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*)</lang> Output:
barfoo
D
<lang d>import std.stdio;
void main() {
string s = "world!"; s = "Hello " ~ s; writeln(s);
}</lang>
- Output:
Hello world!
Déjà Vu
<lang dejavu>local :s "world!" set :s concat( "Hello " s) !print s</lang>
- Output:
Hello world!
Erlang
- Output:
1> S = "world". "world" 2> "Hello " ++ S. "Hello world"
F#
<lang fsharp>let mutable s = "world!" s <- "Hello, " + s printfn "%s" s</lang>
Factor
<lang factor> "world" "Hello " prepend </lang>
Go
<lang go>s := "world!" s = "Hello, " + s</lang>
Haskell
<lang haskell> main = putStrLn ("Hello" ++ "World") </lang>
Icon and Unicon
<lang unicon>s := "world!" s := "Hello, " || s</lang>
J
<lang j> s=: 'value'
s
value
s=: 'new ',s s
new value</lang>
Java
<lang java>public class Prepend {
public static void main(String[] args) { String s = "world!"; System.out.println("Hello " + s); }
}</lang>
Output:
Hello world!
JavaScript
<lang javascript>// No built-in prepend var s=", World" s = "Hello" + s print(s);</lang>
jq
<lang jq>"world!" as $s | "Hello " + $s</lang>
Julia
<lang julia>s = "world!" s = "Hello " * s</lang>
Lasso
<lang Lasso>local(x = ', World!')
- x->merge(1,'Hello')
- x // Hello, World!</lang>
Lua
By concatenation:
<lang lua> s = "12345678" s = "0" .. s print(s)</lang>
By string formatting:
<lang lua> s = "12345678" s = string.format("%s%s", "0", s) print(s)</lang>
By list joining:
<lang lua> s = "12345678" s = table.concat({"0", s}) print(s)</lang>
Output of each solution:
012345678
Mathematica
<lang Mathematica>a = "any text value"; a = "another string literal" <> a (* using concatenation (no built-in prepend) *)</lang>
- Output:
"another string literalany text value"
Mercury
<lang 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).</lang>
- Output:
Hello World!
NetRexx
<lang NetRexx>s_ = 'world!' s_ = 'Hello, 's_ say s_</lang>
- Output:
Hello, world!
NewLISP
<lang NewLISP>(setq str "bar") (push "foo" str) (println str)</lang>
Nimrod
<lang nimrod>var str = "12345678" str = "0" & str echo str</lang>
PARI/GP
Not supported in GP. <lang parigp>s = "world!"; s = Str("Hello, ", s)</lang>
- Output:
%1 = "Hello, world!"
Pascal
<lang Pascal>program StringPrepend; {$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes { you can add units after this };
var
s: String = ' World !';
begin
s := 'Hello' + s; WriteLn(S); ReadLn;
end.</lang> Output:
Hello World !
Perl
<lang perl>my $str = 'bar'; substr $str, 0, 0, 'Foo'; print $str;</lang>
- Output:
Foobar
Perl 6
<lang perl6># 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;</lang>
- Output:
kilobyte megabuck nanobit microfortnight minicooper
PicoLisp
<lang picolisp>(setq Str1 "12345678!") (setq Str1 (pack "0" Str1)) (println Str1)</lang>
- Output:
"012345678!"
PL/I
<lang 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; </lang>
dust bowl
PureBasic
<lang purebasic>S$ = " World!" S$ = "Hello" + S$ If OpenConsole()
PrintN(S$)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole()
EndIf</lang> Sample output:
Hello World!
Python
File: string_prepend.py
<lang python>#!/usr/bin/env python
- -*- coding: utf-8 -*-
s = "12345678" s = "0" + s # by concatenation print(s)</lang>
Output:
012345678
Racket
<lang 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) </lang>
- Output:
bar foo foo bar
REXX
<lang rexx> /*──────────────── using literal abuttal. */
/*──────────────── this won't work is the first */ /*──────────────── variable name is X or B */
zz='llo world!' zz='he'zz say zz
/*──────────────── using literal concatenation. */
gg = "llo world!" gg = 'he' || gg say gg
/*──────────────── using variable concatenation.*/
aString = 'llo world!' bString = "he" aString = bString || aString say aString</lang> output
hello world! hello world! hello world!
Ruby
There is a method for prepending a string, aptly named "prepend". <lang ruby>str = "llo world" str.prepend("He") p str #=> "Hello world"</lang>
Scala
Evaluation in Scala worksheet <lang scala> 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</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
local var string: s is "world!"; begin s := "Hello " & s; writeln(s); end func;</lang>
- Output:
Hello world!
Tcl
Concatenation is a fundamental feature of Tcl's basic language syntax. <lang tcl>set s "llo world" set s "he$s" puts $s</lang>
- Output:
hello world
VBA
<lang VB>Function StringPrepend() Dim s As String s = "bar" s = "foo" & s Debug.Print s End Function</lang>
Wart
<lang python>s <- "12345678" s <- ("0" + s)</lang>
zkl
<lang zkl>s:="bar"; s="foo"+s; s.println(); s:=Data(0,0,"bar").insert(0,"foo").text; s.println();</lang>
- Output:
foobar foobar
- Programming Tasks
- Basic language learning
- String manipulation
- Basic Data Operations
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- Applesoft BASIC
- BBC BASIC
- Bracmat
- C
- C++
- Clojure
- COBOL
- Common Lisp
- D
- Déjà Vu
- Erlang
- F Sharp
- Factor
- Go
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- Lasso
- Lua
- Mathematica
- Mercury
- NetRexx
- NewLISP
- Nimrod
- PARI/GP
- Pascal
- Perl
- Perl 6
- PicoLisp
- PL/I
- PureBasic
- Python
- Racket
- REXX
- Ruby
- Scala
- Seed7
- Tcl
- VBA
- Wart
- Zkl
- Bc/Omit
- Dc/Omit