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 |
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:
- 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". - 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.
[edit] Ada
with Ada.Strings.Fixed, Ada.Text_IO;
use Ada.Strings, Ada.Text_IO;
procedure String_Replace is
Original : constant String := "Mary had a @__@ lamb.";
Tbr : constant String := "@__@";
New_Str : constant String := "little";
Index : Natural := Fixed.Index (Original, Tbr);
begin
Put_Line (Fixed.Replace_Slice (
Original, Index, Index + Tbr'Length - 1, New_Str));
end String_Replace;
[edit] Aikido
const little = "little"
printf ("Mary had a %s lamb\n", little)
// alternatively
println ("Mary had a " + little + " lamb")
[edit] ALGOL 68
strings are simply flex arrays of char. formats on the other hand take on some of the properties of procedures including the scoping rules.
main:(
# as a STRING #
STRING extra = "little";
printf(($"Mary had a "g" lamb."l$, extra));
# as a FORMAT #
FORMAT extraf = $"little"$;
printf($"Mary had a "f(extraf)" lamb."l$);
# or: use simply use STRING concatenation #
print(("Mary had a "+extra+" lamb.", new line))
)
Output:
Mary had a little lamb. Mary had a little lamb. Mary had a little lamb.
[edit] 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%
Documentation: Variables (see Storing values in variables and Retrieving the contents of variables)
[edit] Batch File
@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
Demo
>interpolate.cmd "Mary had a X lamb" little
Mary had a little lamb
[edit] Bracmat
Use pattern matching to find the part of the string up to and the part of the string following the magic X. Concatenate these parts with the string "little" in the middle.
@("Mary had a X lamb":?a X ?z) & str$(!a little !z)
[edit] C
Include the <stdio.h> header to use the functions of the printf family:
#include <stdio.h>
int main() {
const char *extra = "little";
printf("Mary had a %s lamb.\n", extra);
return 0;
}
[edit] C++
#include <string>
#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 ;
}
[edit] C#
This is called "composite formatting" in MSDN.
class Program
{
static void Main()
{
string extra = "little";
string formatted = string.Format("Mary had a {0} lamb.", extra);
System.Console.WriteLine(formatted);
}
}
[edit] Clojure
(let [little "little"]
(println (format "Mary had a %s lamb." little)))
[edit] CoffeeScript
size = 'little'
console.log "Mary had a #{size} lamb." # Mary had a little lamb.
console.log "Escaping: \#{}" # Escaping: #{}
console.log 'No #{ interpolation} with single quotes' # No #{ interpolation} with single quotes
# Multi-line strings and arbtrary expressions work: 20
console.log """
Multi-line strings and arbtrary expressions work: #{ 5 * 4 }
"""
[edit] Common Lisp
(let ((extra "little"))
(format t "Mary had a ~A lamb.~%" extra))
More documentation on the FORMAT function.
[edit] 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);
}
Output:
Mary had a little lamb.
More documentation on the format() function.
[edit] DWScript
PrintLn(Format('Mary had a %s lamb.', ['little']))
Output:
Mary had a little lamb.
[edit] E
def adjective := "little"
`Mary had a $adjective lamb`
The `...` syntax in general may be used as a sort of syntax extension; string interpolation is just the default case. More information on E quasi-literals. (Note that this documentation may be somewhat out of date.)
The above code is equivalent to (expands into):
def adjective := "little"
simple__quasiParser.valueMaker("Mary had a ${0} lamb").substitute([adjective])
If an identifier precedes the opening `, then it replaces simple; the quasiParser may be an arbitrary user-defined object. In this way, E provides lightweight syntax for embedding other languages: XML, JSON, GUI layouts, regular expressions, etc.
[edit] Euphoria
constant lambType = "little"
sequence s
s = sprintf("Mary had a %s lamb.",{lambType})
puts(1,s)
[edit] F#
let lambType = "little"
printfn "Mary had a %s lamb." lambType
[edit] Factor
USE: formatting
SYMBOL: little
"little" little set
little get "Mary had a %s lamb" sprintf
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.
USE: formatting
CONSTANT: little "little"
little "Mary had a %s lamb" sprintf
[edit] Fantom
Interpolating a variable value into a string is done by using a $ prefix on the variable name within a string. For example:
fansh> x := "little"
little
fansh> echo ("Mary had a $x lamb")
Mary had a little lamb
Documentation at: Fantom website
[edit] Fortran
program interpolate
write (*,*) trim(inter("Mary had a X lamb.","X","little"))
contains
elemental function inter(string,place,ins) result(new)
character(len=*), intent(in) :: string,place,ins
character(len=len(string)+max(0,len(ins)-len(place))) :: new
integer :: idx
idx = index(string,place)
if ( idx == 0 ) then
new = string
else
new = string(1:idx-1)//ins//string(idx+len(place):len(string))
end if
end function inter
end program interpolate
[edit] Go
Doc: http://golang.org/pkg/fmt/
package main
import (
"fmt"
)
func main() {
str := "Mary had a %s lamb"
txt := "little"
out := fmt.Sprintf(str, txt)
fmt.Println(out)
}
[edit] Groovy
def adj = 'little'
assert 'Mary had a little lamb.' == "Mary had a ${adj} lamb."
[edit] Haskell
No such facilities are defined in Haskell 98, but the base package distributed with GHC provides a printf function.
import Text.Printf
main = printf "Mary had a %s lamb\n" "little"
[edit] HicEst
Further documentation on HicEst string interpolation function EDIT()
CHARACTER original="Mary had a X lamb", little = "little", output_string*100
output_string = original
EDIT(Text=output_string, Right='X', RePLaceby=little)
[edit] 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
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
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.
[edit] J
The strings and printf scripts are part of the base library.
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.
Documentation:
The comments in these library files give brief descriptions of their contents, and you can browse them using open:
open'strings printf'
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).
[edit] 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);
[edit] JavaScript
var original = "Mary had a X lamb";
var little = "little";
var replaced = original.replace("X", little); //does not change the original string
[edit] Lua
[edit] Variable names
There is no default support for automatic interpolation of variables names being used as placeholders within a string. However, interpolation is easily emulated by using the [string.gsub] function:
str = string.gsub( "Mary had a X lamb.", "X", "little" )
print( str )
[edit] Literal characters
Interpolation of literal characters escape sequences does occur within a string:
print "Mary had a \n lamb" -- The \n is interpreted as an escape sequence for a newline
[edit] Mathematica
Extra = "little";
StringReplace["Mary had a X lamb.", {"X" -> Extra}]
->"Mary had a little lamb."
[edit] Maxima
printf(true, "Mary had a ~a lamb", "little");
[edit] Nemerle
Nemerle has a few ways to accomplish this. It provides an implementation of printf(), $ interpolation within the print() method, and the most general use is $ interpolation within $ quoted strings.
using System;
using System.Console;
using Nemerle.IO; // contains printf() and print()
module Stringy
{
Main() : void
{
def extra = "little";
printf("Mary had a %s lamb.\n", extra);
print("Mary had a $extra lamb.\n");
WriteLine($"Mary had a $extra lamb.");
}
}
[edit] NetRexx
The Built In Functions (BIFs) of NetRexx can be employed to manipulate strings quite successfully but for more flexible string interpolation a function package like Java's MessageFormat should be used.
/* NetRexx */
options replace format comments java crossref savelog symbols
import java.text.MessageFormat
import java.text.FieldPosition
useBif()
useMessageFormat()
return
method useBif public static
st = "Mary had a %1$ lamb."
si = 'little'
say st.changestr('%1$', si)
return
method useMessageFormat public static
result = StringBuffer('')
args = Object [ -
Object Integer(7), -
Object Date(), -
Object 'a disturbance in the Force' -
]
msgfmt = MessageFormat('At {1, time} on {1, date}, there was {2} on planet {0, number, integer}.')
result = msgfmt.format(args, result, FieldPosition(0))
say result
return
- Output
Mary had a little lamb. At 5:43:05 PM on Aug 22, 2011, there was a disturbance in the Force on planet 7.
[edit] OCaml
The OCaml standard library provides the module Printf:
let extra = "little" in
Printf.printf "Mary had a %s lamb." extra
[edit] 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.
declare
X = "little"
in
{System.showInfo "Mary had a "#X#" lamb"}
[edit] PARI/GP
The Pari library has string interpolation, which extends C's:
GEN
string_interpolate(GEN n)
{
pari_printf("The value was: %Ps.\n", n);
GEN s = pari_sprintf("Storing %Ps in a string", n);
}
GP can also interpolate strings:
s=Strprintf("The value was: %Ps", 1<<20);
printf("The value was: %Ps", 1<<20);
[edit] Perl
$extra = "little";
print "Mary had a $extra lamb.\n";
printf "Mary had a %s lamb.\n", $extra;
[edit] Perl 6
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
[edit] PHP
<?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
[edit] PicoLisp
(let Extra "little"
(prinl (text "Mary had a @1 lamb." Extra)) )
[edit] Prolog
Extra = little,
format('Mary had a ~w lamb.', [Extra]), % display result
format(atom(Atom), 'Mary had a ~w lamb.', [Extra]). % ... or store it a variable
[edit] PureBasic
The function ReplaceString() is built-in and can have both constants and variables as parameters.
ReplaceString("Mary had a X lamb.","X","little")
Implemented in a program context
; 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
[edit] 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:
>>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'
Using the .format method of strings:
>>> original = 'Mary had a {extra} lamb.'
>>> extra = 'little'
>>> original.format(**locals())
'Mary had a little lamb.'
Using the format method, but replace by an expressions position as an argument to the format method call instead of by name:
>>> original = 'Mary had a {0} lamb.'
>>> extra = 'little'
>>> original.format(extra)
'Mary had a little lamb.'
Using the Template class of the string module:
>>> from string import Template
>>> original = Template('Mary had a $extra lamb.')
>>> extra = 'little'
>>> original.substitute(**locals())
'Mary had a little lamb.'
[edit] Racket
See the documentation on fprintf for more information on string interpolation in Racket.
#lang racket
(format "Mary had a ~a lamb" "little")
[edit] 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"]
[edit] REXX
Interpolation does not occur in literal strings, neither within singlequote or doublequote enclosures. However, interpolation can be emulated using the changestr function:
/*REXX program to demonstrate string interpolation (string replacement).*/
/*the string to be replaced is */
replace = "little" /*usually a unique character(s) */
/*string and is case sensative.*/
original1 = "Mary had a X lamb."
new1 = changestr('X', original1, replace)
say 'original1 =' original1
say 'replaced =' new1
say
original2 = "Mary had a % lamb."
new2 = changestr('%', original2, replace)
say 'original2 =' original2
say 'replaced =' new2
say
original3 = "Mary had a $$$ lamb."
new3 = changestr('$$$',original3,replace)
say 'original3 =' original3
say 'replaced3 =' new3
say
original4 = "Mary had a someKindOf lamb."
new3 = changestr('someKindOf', original4, "little")
say 'original4 =' original4
say 'replaced4 =' new3
/*stick a fork in it, we're done.*/
Some older REXXes don't have a changestr bif, so one is included here ──► CHANGESTR.REX.
output
original1 = Mary had a X lamb. replaced = Mary had a little lamb. original2 = Mary had a % lamb. replaced = Mary had a little lamb. original3 = Mary had a $$$ lamb. replaced3 = Mary had a little lamb. original4 = Mary had a someKindOf lamb. replaced4 = Mary had a little lamb.
[edit] 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."
Documentation:
- string_spec.rb describes interpolation using #{....} in double-quoted strings.
- Core API describes printf-style interpolation by String#% and Kernel#sprintf.
[edit] Run BASIC
a$ = Mary had a X lamb."
a$ = word$(a$,1,"X")+"little"+word$(a$,2,"X")
[edit] Scala
Scala 2.10.0 supports direct string interpolation by putting "s" at the beginning of the string:
val extra = "little"
val result = s"Mary had a $extra lamb."
Result:
Mary had a little lamb.
When using an older version of Scala, do this instead:
val original = "Mary had a %s lamb."
val extra = "little"
original format extra
Result:
Mary had a little lamb.
Documentation:
- Scala 2.10.0: string interpolation
[edit] Sed
#!/bin/bash
# Usage example: . interpolate "Mary has a X lamb" "quite annoying"
echo "$1" | sed "s/ X / $2 /g"
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
const string: original is "Mary had a X lamb";
const string: little is "little";
var string: replaced is "";
begin
replaced := replace(original, "X", little);
writeln(replaced);
end func;
Output:
Mary had a little lamb
[edit] SNOBOL4
Every statement in SNOBOL can is a subset of pattern replacement having a subject (s1 in this case), object (s2), and replacement (s3).
s1 = "Mary had a humongous lamb."
s2 = "humongous"
s3 = "little"
s1 s2 = s3
end
See The SNOBOL4 Programming Language; Griswold, Poage, Polonsky; Chapter 2 Pattern Matching
[edit] 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.
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."
When more sophisticated control is required the format command can be used, which is very similar to the standard C library's sprintf function:
puts [format "Mary had a %s %s." [RandomWord little big] [RandomWord lamb piglet calf]]
A third approach is to use string map.
set s "Mary had a @SIZE@ lamb."
puts [string map {@SIZE@ "miniscule"} $s]
Tcl also supports variable variable names. Even more powerful is nested interpolation with the subst command.
set grandpa {$daddy}; set grandma \$mommy
set daddy myself; set mommy {lil' bro}
set fun1 \[string\ to
set fun2 lower
set lower middle
set middle upper
set fun3 {aNd]}
puts [subst "$grandpa $fun1$[subst $$fun2] $fun3 $grandma"]
[edit] TUSCRIPT
$$ MODE TUSCRIPT
sentence_old="Mary had a X lamb."
values=*
DATA little
DATA big
sentence_new=SUBSTITUTE (sentence_old,":X:",0,0,values)
PRINT sentence_old
PRINT sentence_new
Output:
Mary had a X lamb. Mary had a little lamb.
[edit] UNIX Shell
Within the Unix shell, interpolation only occurs within doublequotes. Strings enclosed in singlequotes will not be subject to interpolation. Note that within the shell, a string may be used bare. If this is done each word within the string is treated separately, and any variable references or escape sequences will be substituted for their values:
extra='little'
echo Mary had a $extra lamb.
echo "Mary had a $extra lamb."
printf "Mary had a %s lamb.\n" $extra
A parameter substitution, like $extra or ${extra}, interpolates its value into some string. This happens outside quotes or inside "double quotes". The other form of interpolation is printf(1) with %s.
The shell has more forms of parameter substitution, like ${tea:?no tea}. Your shell's manual explains those. For the original Bourne Shell, sh(1) manual explains those.
[edit] C Shell
set extra='little'
echo Mary had a $extra lamb.
echo "Mary had a $extra lamb."
printf "Mary had a %s lamb.\n" $extra
C Shell has $extra and ${extra}. There are also modifiers, like $file:t; csh(1) manual explains those.
[edit] Ursala
Expressions like this
-[foo-[ x ]-bar]-
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
-[foo-[. f ]-bar]-
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.
x = <'little'>
#show+
main = -[Mary had a -[. ~& ]- lamb.]- x
These operators are parsed like parentheses. Here is the output.
Mary had a little lamb.
[edit] VBA
Visual Basic for Applications has a built-in function Replace.
Example dialog (in the immediate window):
a="little"
print replace("Mary had a X lamb","X",a)
Mary had a little lamb
Function Replace has 3 mandatory and 3 optional arguments:
- the input string
- the substring that is to be replaced
- the string that is to replace the substring
- optional: the position in the input string where to start replacing (default 1)
- optional: the number of replacements to make (default -1, i.e. all)
- optional: the comparison method: vbBinaryCompare or vbTextCompare (text compare is not case sensitive: it will replace "%X" as well as "%x". vbBinaryCompare will only replace %X. Default value depends on the setting of the standard comparison method (set with Option Compare Binary or Option Compare Text).
- Programming Tasks
- Basic language learning
- String manipulation
- Basic Data Operations
- NSIS/Omit
- BBC BASIC/Omit
- Ada
- Aikido
- ALGOL 68
- AutoHotkey
- Batch File
- Bracmat
- C
- C++
- C sharp
- Clojure
- CoffeeScript
- Common Lisp
- D
- DWScript
- E
- Euphoria
- F Sharp
- Factor
- Fantom
- Fortran
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- Icon Programming Library
- J
- Java
- JavaScript
- Lua
- Mathematica
- Maxima
- Nemerle
- NetRexx
- OCaml
- Oz
- PARI/GP
- Perl
- Perl 6
- PHP
- PicoLisp
- Prolog
- PureBasic
- Python
- Racket
- REBOL
- REXX
- Ruby
- Run BASIC
- Scala
- Sed
- Seed7
- SNOBOL4
- Tcl
- TUSCRIPT
- UNIX Shell
- C Shell
- Ursala
- VBA
- 8086 Assembly/Omit
- 80386 Assembly/Omit
- GUISS/Omit
- Unlambda/Omit
- Z80 Assembly/Omit