String prepend: Difference between revisions
No edit summary |
|||
Line 450: | Line 450: | ||
dust bowl |
dust bowl |
||
</pre> |
</pre> |
||
=={{header|PowerShell}}== |
|||
<lang PowerShell> |
|||
$str = "World!" |
|||
$str = "Hello, " + $str |
|||
$str |
|||
</lang> |
|||
<pre>Hello, World!</pre> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
Revision as of 20:39, 1 June 2015
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
C#
<lang csharp>using System;
namespace PrependString {
class Program { static void Main(string[] args) { string str = "World"; str = "Hello " + str; Console.WriteLine(str); Console.ReadKey(); } }
}</lang>
Hello World
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"
ERRE
<lang ERRE> ...... S$=" World!" S$="Hello"+S$ PRINT(S$) ...... </lang>
- Output:
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> Prelude> let f = (++" World!") Prelude> f "Hello" </lang>
- Output:
"Hello world!"
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>
LFE
Using the concatenation operator:
<lang lisp> > (set s "world") "world" > (++ "hello " s) "hello world" </lang>
Using the concatenation function:
<lang lisp> > (set s "world") "world" > (string:concat "hello " s) "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>
Nim
<lang nim>var str = "12345678" str = "0" & str echo str</lang>
Oforth
<lang Oforth>" World" "Hello" swap + println</lang>
- Output:
Hello World
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
PowerShell
<lang PowerShell> $str = "World!" $str = "Hello, " + $str $str </lang>
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:
<lang prolog>
- - 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).
</lang>
Example of this abomination in action:
<lang prolog> ?- Str = `World!`, `Hello, ` =+ Str. Str = "Hello, World!".</lang>
Note: I can't imagine when I would want to do this in Prolog.
PureBasic
<lang purebasic>S$ = " World!" S$ = "Hello" + S$ If OpenConsole()
PrintN(S$)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole()
EndIf</lang>
- 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 as 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!
Sidef
<lang ruby>var str = 'llo!'; str.sub!(/^/, 'He'); say str;</lang>
- Output:
Hello!
Swift
<lang Swift>var str = ", World" str = "Hello \(str)" println(str)</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>
VBScript
<lang vb>s = "bar" s = "foo" & s WScript.Echo s</lang>
- Output:
foobar
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
- Basic Data Operations
- String manipulation
- Simple
- Bc/Omit
- Dc/Omit
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- Applesoft BASIC
- BBC BASIC
- Bracmat
- C
- C++
- C sharp
- Clojure
- COBOL
- Common Lisp
- D
- Déjà Vu
- Erlang
- ERRE
- F Sharp
- Factor
- Go
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- Lasso
- LFE
- Lua
- Mathematica
- Mercury
- NetRexx
- NewLISP
- Nim
- Oforth
- PARI/GP
- Pascal
- Perl
- Perl 6
- PicoLisp
- PL/I
- PowerShell
- Prolog
- PureBasic
- Python
- Racket
- REXX
- Ruby
- Scala
- Seed7
- Sidef
- Swift
- Tcl
- VBA
- VBScript
- Wart
- Zkl