String prepend: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 285: Line 285:
This demonstration code 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. The memory format here is a simple count+text. Strings in Forth return their address, or their address and length onto the data stack and 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.
This demonstration code 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. The memory format here is a simple count+text. Strings in Forth return their address, or their address and length onto the data stack and 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.


<lang Forth>: C+! ( n addr -- ) DUP C@ ROT + SWAP C! ; \ primitive: increment a byte at addr by n
<lang>: 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
: +PLACE ( addr1 length addr2 -- ) \ Append addr1 length to addr2
Line 306: Line 306:


Test our language extensions interactively at the console
Test our language extensions interactively at the console
{{Output}}
<pre>
<pre>
string1 writeln
string1 writeln

Revision as of 21:19, 8 February 2016

Task
String prepend
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.

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.

<lang Ada>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;</lang>

Output:
Hello World!

ALGOL 68

Works with: ALGOL 68 version Revision 1.
Works with: ALGOL 68G version Any - tested with release algol68g-2.7.
Works with: ELLA ALGOL 68 version Any (with appropriate job cards).

File: String_prepend.a68<lang algol68>#!/usr/bin/a68g --script #

  1. -*- 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>

  1. 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

Works with: Applesoft BASIC

BBC BASIC

Works with: BBC BASIC

Bracmat

<lang bracmat> World!:?string & str$("Hello " !string):?string & out$!string</lang>

Hello World!

C

<lang c>#include<stdio.h>

  1. include<string.h>
  2. 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>

  1. include <algorithm>
  2. include <string>
  3. 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

Works with: GNU Cobol version 2.0

<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!

EchoLisp

<lang scheme> 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"

</lang>

Elena

<lang elena>#import system.

  1. symbol program =

[

   #var s := "World".
   s := "Hello " + s.
   console writeLine:s.
   
   // Alternative way
   #var s2 := String new:"World".
   s2 insert:"Hello " &at:0.
   console writeLine:s2.

].</lang>


Elixir

<lang Elixir> str1 = "World!" str = "Hello, " <> str1 </lang>

Output:

"Hello, World!"

Emacs Lisp

version 1

<lang Emacs Lisp> (defun glue (str1 str2)

 (concat str1 str2) )

</lang>

version 2

<lang Emacs Lisp> (defun glue (str1 str2)

 (format "%s%s" str1 str2) )

</lang> Eval: <lang Emacs Lisp> (setq str "World!") (setq str (glue "Hello, " str) ) (insert str) </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>

Forth

This demonstration code 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. The memory format here is a simple count+text. Strings in Forth return their address, or their address and length onto the data stack and 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.

<lang>: 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! ;

256 buffer: string1 \ buffer: is Forth 2012 word

s" needs no introducton!" STRING1 PLACE \ initialize our string

PREPEND ( addr len addr2 -- addr)
          >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
writeln ( addr -- ) cr count type ; \ syntax sugar</lang>

Test our language extensions interactively at the console

Output:
string1 writeln 
needs no introduction! ok

s" This string "  string1 PREPEND writeln
This string needs no introduction! ok<pre>

=={{header|Go}}==
<lang go>s := "world!"
s = "Hello, " + s</lang>

=={{header|Haskell}}==
<lang haskell>
Prelude> let f = (++" World!")
Prelude> f "Hello"
</lang>

{{out}}
<pre>"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!')

  1. x->merge(1,'Hello')
  2. 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>

LiveCode

The idiomatic way is to use "before"<lang LiveCode>put "world" into x put "hello" before x put 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>

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

Works with: Free Pascal version 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

 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;

  1. interpolation as concatenation

$_ = 'buck'; $_ = "mega$_"; .say;

  1. lvalue substr

$_ = 'bit'; substr-rw($_,0,0) = 'nano'; .say;

  1. regex substitution

$_ = 'fortnight'; s[^] = 'micro'; .say;

  1. 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

Works with: SWI-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

  1. -*- 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>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</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>

or <lang ruby>var str = 'llo!'; str.prepend!('He'); say str;</lang>

Output:
Hello!

SNOBOL4

<lang SNOBOL4> s = ', World!'

   OUTPUT = s = 'Hello' s

END</lang>

Output:
Hello, World!

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