String interpolation (included): Difference between revisions

From Rosetta Code
Content added Content deleted
(Go solution)
Line 166: Line 166:
little "Mary had a %s lamb" sprintf</lang>
little "Mary had a %s lamb" sprintf</lang>
=={{header|Go}}==
=={{header|Go}}==
Doc: [http://golang.org/pkg/fmt/]
Doc: [http://golang.org/pkg/fmt/ http://golang.org/pkg/fmt/]
<lang go>
<lang go>
package main
package main

Revision as of 22:23, 7 January 2011

Task
String interpolation (included)
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

Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.

For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb".
(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").

The task is to:

  1. Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb".
  2. If possible, give links to further documentation on your languages string interpolation features.

Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.

Aikido

<lang aikido>const little = "little" printf ("Mary had a %s lamb\n", little)

// alternatively println ("Mary had a " + little + " lamb")</lang>

ALGOL 68

Translation of: C
Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

strings are simply flex arrays of char. formats on the other hand take on some of the properties of procedures including the scoping rules. <lang algol68>main:(

  1. as a STRING #
 STRING extra = "little";
 printf(($"Mary had a "g" lamb."l$, extra));
  1. as a FORMAT #
 FORMAT extraf = $"little"$;
 printf($"Mary had a "f(extraf)" lamb."l$);
  1. or: use simply use STRING concatenation #
 print(("Mary had a "+extra+" lamb.", new line))

)</lang> Output:

Mary had a little lamb.
Mary had a little lamb.
Mary had a little lamb.

AutoHotkey

<lang AutoHotkey>; Using the = operator LIT = little string = Mary had a %LIT% lamb.

Using the
= operator

LIT := "little" string := "Mary had a" LIT " lamb."

MsgBox %string%</lang>

Documentation: Variables (see Storing values in variables and Retrieving the contents of variables)

Batch File

<lang dos>@echo off setlocal enabledelayedexpansion call :interpolate %1 %2 res echo %res% goto :eof

interpolate

set pat=%~1 set str=%~2 set %3=!pat:X=%str%! goto :eof</lang>

Demo <lang dos>>interpolate.cmd "Mary had a X lamb" little Mary had a little lamb</lang>

C

Include the <stdio.h> header to use the functions of the printf family: <lang c>#include <stdio.h>

int main() {

 char *extra = "little";
 printf("Mary had a %s lamb.\n", extra);
 return 0;

}</lang>

C++

<lang C++>#include <string>

  1. include <iostream>

int main( ) {

  std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
     replacement ( "little" ) ;
  std::string newString = original.replace( original.find( "X" ) ,

toBeReplaced.length( ) , replacement ) ;

  std::cout << "String after replacement: " << newString << " \n" ;
  return 0 ;

}</lang>

C#

This is called "composite formatting" in MSDN.

<lang csharp>class Program {

   static void Main()
   {
       string extra = "little";
       string formatted = string.Format("Mary had a {0} lamb.", extra);
       System.Console.WriteLine(formatted);
   }

}</lang>

Clojure

<lang lisp>(let [little "little"]

 (println (format "Mary had a %s lamb." little)))</lang>

Common Lisp

<lang lisp>(let ((extra "little"))

 (format t "Mary had a ~A lamb.~%" extra))

</lang>

More documentation on the FORMAT function.

D

<lang d>import std.stdio: writeln; import std.string: format;

void main() {

   auto original = "Mary had a %s lamb.";
   auto extra = "little";
   auto modified = format(original, extra);
   writeln(modified);

}</lang> Output:

Mary had a little lamb.

More documentation on the format() function.

E

This example is in need of improvement:

Add links to documentation.

<lang e>def adjective := "little" `Mary had a $adjective lamb`</lang>

F#

Documentation <lang fsharp> let lambType = "little" printfn "Mary had a %s lamb." lambType </lang>

Factor

<lang factor>USE: formatting

SYMBOL: little

"little" little set

little get "Mary had a %s lamb" sprintf</lang>

I tried to be as specific as possible here. The challenge says to use a variable so that is what I used. It could have been done more cleanly using a CONSTANT.

<lang factor>USE: formatting

CONSTANT: little "little"

little "Mary had a %s lamb" sprintf</lang>

Go

Doc: http://golang.org/pkg/fmt/ <lang go> package main

import (

   "fmt"

)

func main() {

   s := fmt.Sprintf("Mary had a %s lamb", "little")
   fmt.Println(s)

} </lang>

Haskell

No such facilities are defined in Haskell 98, but the base package distributed with GHC provides a printf function.

<lang haskell>import Text.Printf

main = printf "Mary had a %s lamb\n" "little"</lang>

HicEst

Further documentation on HicEst string interpolation function EDIT() <lang hicest>CHARACTER original="Mary had a X lamb", little = "little", output_string*100

output_string = original EDIT(Text=output_string, Right='X', RePLaceby=little)</lang>

Icon and Unicon

Icon and Unicon are descended from a line of languages with a wealth of string manipulation capabilities. See The Icon Programming Language, 3rd Edition; Griswold and Griswold; Chapter 3 String Scanning

Icon

<lang Icon> s2 := "humongous"

 s3 := "little"
 s1 :=  "Mary had a humongous lamb."
 s1 ?:= tab(find(s2)) || (=s2,s3) || tab(0)          # replaces the first instance of s2 with s3
 while s1 ?:= tab(find(s2)) || (=s2,s3) || tab(0)    # replaces all instances of s2 with s3, equivalent to replace</lang>

Note the strings library includes convenient procedures for string replacement such as replace(s1,s2,s3) which replaces all occurrences of s2 in s1 with s3 and replacem(s1,s2,s3,...) which replaces multiple pairs.

Unicon

This Icon solution works in Unicon.

J

The strings and printf scripts are part of the base library. <lang j> require 'printf'

  'Mary had a %s lamb.' sprintf <'little'

Mary had a little lamb.

  require 'strings'
  ('%s';'little') stringreplace 'Mary had a %s lamb.'

Mary had a little lamb.

  'Mary had a %s lamb.' rplc '%s';'little'

Mary had a little lamb.</lang>

Documentation:

The comments in these library files give brief descriptions of their contents, and you can browse them using open:

<lang J> open'strings printf'</lang>

Alternatively, both strings and printf have various web pages describing them, and printf has a lab demonstrating its use (from J's IDE's menu, go Studio -> Labs... and then look in the System category).

Java

<lang java>String original = "Mary had a X lamb"; String little = "little"; String replaced = original.replace("X", little); //does not change the original String System.out.println(replaced); //Alternative: System.out.printf("Mary had a %s lamb.", little); //Alternative: String formatted = String.format("Mary had a %s lamb.", little); System.out.println(formatted);</lang>

JavaScript

<lang javascript>var original = "Mary had a X lamb"; var little = "little"; var replaced = original.replace("X", little); //does not change the original string</lang>

Lua

<lang Lua>str = string.gsub( "Mary had a X lamb.", "X", "little" ) print( str )</lang>

OCaml

The OCaml standard library provides the module Printf:

<lang ocaml>let extra = "little" in Printf.printf "Mary had a %s lamb." extra</lang>

Oz

String interpolation is unidiomatic in Oz. Instead, "virtual strings" are used. Virtual strings are tuples of printable values and are supported by many library functions.

<lang oz>declare

 X = "little"

in

 {System.showInfo "Mary had a "#X#" lamb"}</lang>

PARI/GP

The Pari library has string interpolation, which extends C's: <lang C>GEN string_interpolate(GEN n) {

 pari_printf("The value was: %Ps.\n", n);
 GEN s = pari_sprintf("Storing %Ps in a string", n);

}</lang>

Works with: PARI/GP version version 2.4.4 and above

GP can also interpolate strings: <lang>s=Strprintf("The value was: %Ps", 1<<20); printf("The value was: %Ps", 1<<20);</lang>

Perl

<lang perl>$extra = "little"; print "Mary had a $extra lamb.\n"; printf "Mary had a %s lamb.\n", $extra;</lang>

Perl 6

<lang perl6>my $extra = "little"; say "Mary had a $extra lamb"; # variable interpolation say "Mary had a { $extra } lamb"; # expression interpolation printf "Mary had a %s lamb.\n", $extra; # standard printf say $extra.fmt("Mary had a %s lamb"); # inside-out printf</lang>

PHP

<lang php><?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?></lang>

PicoLisp

<lang PicoLisp>(let Extra "little"

  (prinl (text "Mary had a @1 lamb." Extra)) )</lang>

PureBasic

The function ReplaceString() is built-in and can have both constants and variables as parameters. <lang PureBasic>ReplaceString("Mary had a X lamb.","X","little")</lang> Implemented in a program context <lang PureBasic>; String variable can be defined by appending .s to its name during definition or by appending and using $ as a part of its name. Define txt$, txtvar.s="little"

Load datasegment into variable txt$

Restore Mary Read.s txt$

Replace X with "little" and store result in txt$

txt$=ReplaceString(txt$,"X",txtvar)

OpenConsole(): Print(txt$)

DataSection:

 Mary:
 Data.s  "Mary had a X lamb."

EndDataSection</lang>

Python

Python has more than one inbuilt way of accomplishing the task. The methods have different capabilities that are not stretched by this small task

Using the % string interpolation operator: <lang python>>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'</lang>

Using the .format method of strings: <lang python>>>> original = 'Mary had a {extra} lamb.' >>> extra = 'little' >>> original.format(**locals()) 'Mary had a little lamb.'</lang> Using the format method, but replace by an expressions position as an argument to the format method call instead of by name: <lang python>>>> original = 'Mary had a {0} lamb.' >>> extra = 'little' >>> original.format(extra) 'Mary had a little lamb.'</lang>


Using the Template class of the string module: <lang python>>>> from string import Template >>> original = Template('Mary had a $extra lamb.') >>> extra = 'little' >>> original.substitute(**locals()) 'Mary had a little lamb.'</lang>

REBOL

<lang rebol>str: "Mary had a <%size%> lamb" size: "little" build-markup str

REBOL3 also has the REWORD function

str: "Mary had a $size lamb" reword str [size "little"]</lang>

REXX

<lang rexx> original="Mary had a % lamb."

replace ="little"

new =changestr('%',original,replace)

say 'original='original say 'replaced='new </lang> Output:

original=Mary had a % lamb.
replaced=Mary had a little lamb.

Ruby

<lang ruby> irb(main):001:0> extra = 'little' => "little" irb(main):002:0> "Mary had a #{extra} lamb." => "Mary had a little lamb." irb(main):003:0> "Mary had a %s lamb." % extra => "Mary had a little lamb." </lang>

Scala

<lang scala> val original = "Mary had a %s lamb." val extra = "little" original format extra </lang> Result: <lang>Mary had a little lamb.</lang>

SNOBOL4

Every statement in SNOBOL can is a subset of pattern replacement having a subject (s1 in this case), object (s2), and replacement (s3). <lang snobol> s1 = "Mary had a humongous lamb." s2 = "humongous"

       s3 = "little"           

s1 s2 = s3 end</lang> See The SNOBOL4 Programming Language; Griswold, Poage, Polonsky; Chapter 2 Pattern Matching

Tcl

String interpolation is a fundamental operation of the Tcl language itself, and is carried out in a "double-quoted" program strings as well as bare-words. Thus, interpolation of the string from a variable is carried out with the $ syntax and the string result of a command is interpolated with the […] syntax. <lang tcl>set size "little" puts "Mary had a $size lamb."

proc RandomWord {args} {

  lindex $args [expr {int(rand()*[llength $args])}]

} puts "Mary had a [RandomWord little big] lamb."</lang> When more sophisticated control is required the format command can be used, which is very similar to the standard C library's sprintf function: <lang tcl>puts [format "Mary had a %s %s." [RandomWord little big] [RandomWord lamb piglet calf]]</lang>

A third approach is to use string map. <lang tcl>set s "Mary had a @SIZE@ lamb." puts [string map {@SIZE@ "miniscule"} $s]</lang>

UNIX Shell

Works with: Bourne Again SHell

<lang bash>EXTRA='little' echo "Mary had a $EXTRA lamb." printf "Mary had a %s lamb.\n" $EXTRA</lang>

Ursala

Expressions like this <lang Ursala>-[foo-[ x ]-bar]-</lang> evaluate to a list of character strings beginning with foo and ending with bar, where foo and bar are literal text (possibly multiple lines) and x is any expression evaluating to a list of character strings. Using a dot like this <lang Ursala>-[foo-[. f ]-bar]-</lang> makes it a function returning a list of character strings consisting of the output from the function f bracketed by the literal text foo and bar. In this task, the identity function, ~&, is used for f. <lang Ursala>x = <'little'>

  1. show+

main = -[Mary had a -[. ~& ]- lamb.]- x</lang> These operators are parsed like parentheses. Here is the output.

Mary had a little lamb.