String-Interpolation - String interpolation
In der Computerprogrammierung ist die Zeichenfolgeninterpolation (oder Variableninterpolation , Variablensubstitution oder Variablenerweiterung ) der Prozess der Auswertung eines Zeichenfolgenliterals, das einen oder mehrere Platzhalter enthält , was zu einem Ergebnis führt, bei dem die Platzhalter durch ihre entsprechenden Werte ersetzt werden. Es ist eine Form der einfachen Template-Verarbeitung oder, formal ausgedrückt, eine Form des Quasi-Zitats (oder der logischen Substitutionsinterpretation ). String - Interpolation ermöglicht eine leichtere und intuitivere String Formatierung und Inhalt-Spezifikation verglichen mit String - Verkettung .
String-Interpolation ist in vielen Programmiersprachen üblich, die stark von String- Darstellungen von Daten Gebrauch machen , wie Apache Groovy , Julia , Kotlin , Perl , PHP , Python , Ruby , Scala , Swift , Tcl und die meisten Unix-Shells . Normalerweise werden zwei Modi für wörtliche Ausdrücke angeboten: einer mit aktivierter Interpolation, der andere ohne (als Rohstring bezeichnet ). Platzhalter werden normalerweise durch ein bloßes oder ein benanntes Siegel (normalerweise $
oder %
) dargestellt, zB $placeholder
oder %123
. Die Erweiterung des Strings erfolgt normalerweise zur Laufzeit .
Variationen
Einige Sprachen bieten keine String-Interpolation an, sondern bieten stattdessen eine Standardfunktion an, bei der ein Parameter der printf-Formatstring ist und andere die Werte für jeden Platzhalter bereitstellen.
Ruby verwendet das #
Symbol für die Interpolation und ermöglicht die Interpolation jedes Ausdrucks, nicht nur von Variablen. Andere Sprachen unterstützen möglicherweise eine erweiterte Interpolation mit einer speziellen Formatierungsfunktion, z. B. printf
, bei der das erste Argument, das Format , das Muster angibt, in dem die restlichen Argumente ersetzt werden.
Algorithmen
Es gibt zwei Haupttypen von Erweiterungsalgorithmen für die Variableninterpolation :
- Ersetzen und Erweitern von Platzhaltern : Erstellen einer neuen Zeichenfolge aus der ursprünglichen Zeichenfolge durch Suchen-Ersetzen-Operationen. Variablenreferenz (Platzhalter) suchen und durch ihren Variablenwert ersetzen. Dieser Algorithmus bietet keine Cache-Strategie.
- String teilen und verbinden : den String in ein Array aufteilen und mit dem entsprechenden Array von Werten zusammenführen; dann verbinden Sie Elemente durch Verkettung. Die geteilte Zeichenfolge kann zur Wiederverwendung zwischengespeichert werden.
Sicherheitsprobleme
Die Stringinterpolation kann wie die Stringverkettung zu Sicherheitsproblemen führen. Wenn Benutzereingabedaten nicht ordnungsgemäß maskiert oder gefiltert werden, ist das System SQL-Injection- , Script-Injection- , XML External Entity Injection- (XXE) und Cross-Site-Scripting- (XSS-) Angriffen ausgesetzt.
Ein SQL-Injection-Beispiel:
query = "SELECT x, y, z FROM Table WHERE id='$id'
"
Wenn $id
durch " "';
ersetzt wird, löscht die Ausführung dieser Abfrage alle Daten in Table.
DELETE FROM Table; SELECT * FROM Table WHERE id='
Beispiele
Der folgende Perl- Code funktioniert in PHP identisch :
$name = "Alice";
print "${name} said Hello World to the crowd of people.";
erzeugt die Ausgabe: Alice said Hello World to the crowd of people.
ABAP
DATA(apples) = 4.
WRITE |I have { apples } apples|.
Die Ausgabe wird sein:
I have 4 apples
Bash
apples=4
echo "I have $apples apples"
# or
echo "I have ${apples} apples"
Die Ausgabe wird sein:
I have 4 apples
Boo
apples = 4
print("I have $(apples) apples")
# or
print("I have {0} apples" % apples)
Die Ausgabe wird sein:
I have 4 apples
C#
var apples = 4;
var bananas = 3;
Console.WriteLine($"I have {apples} apples");
Console.WriteLine($"I have {apples + bananas} fruits");
Die Ausgabe wird sein:
I have 4 apples
I have 7 fruits
ColdFusion-Markup-Sprache
ColdFusion Markup Language (CFML)-Skriptsyntax:
apples = 4;
writeOutput("I have #apples# apples");
Tag-Syntax:
<cfset apples = 4>
<cfoutput>I have #apples# apples</cfoutput>
Die Ausgabe wird sein:
I have 4 apples
KaffeeScript
apples = 4
console.log "I have #{apples} apples"
Die Ausgabe wird sein:
I have 4 apples
Pfeil
int apples = 4, bananas = 3;
print('I have $apples apples.');
print('I have ${apples+bananas} fruit.');
Die Ausgabe wird sein:
I have 4 apples.
I have 7 fruit.
gehen
lang := "Golang"
apples := 3
fmt.Printf("I am a %s developer.\n", lang)
fmt.Printf("I have %d apples.\n", apples)
Die Ausgabe wird sein:
I am a Golang developer.
I have 3 apples.
Groovig
In groovigen, interpolierten Strings werden GStrings genannt:
def quality = "superhero"
final age = 52
def sentence = "A developer is a $quality, if he is ${age <= 42 ? "young" : "seasoned"}"
println sentence
Die Ausgabe wird sein:
A developer is a superhero if he is seasoned
Haxe
var apples = 4;
var bananas = 3;
trace('I have $apples apples.');
trace('I have ${apples+bananas} fruit.');
Die Ausgabe wird sein:
I have 4 apples.
I have 7 fruit.
Java
Da es keine echten interpolierten Zeichenfolgen gibt, verwendet Java Hilfsfunktionen als Problemumgehung.
In Java-Versionen 5 und höher kann die statische Methode String.format
zur Interpolation verwendet werden:
int apples = 4;
int bananas = 3;
System.out.println(String.format("I have %s apples and %s bananas", apples, bananas));
System.out.println(String.format("I have %s fruit", apples + bananas));
In Java Version 1.1 und höher kann die MessageFormat
Klasse Objektgruppen mithilfe von Platzhaltern formatieren:
Object[] testArgs = {Long.valueOf(3), "MyDisk"};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
JavaScript
JavaScript unterstützt ab dem ECMAScript 2015 (ES6)-Standard die String-Interpolation mit Backticks ``
. Diese Funktion wird als Vorlagenliterale bezeichnet . Hier ist ein Beispiel:
const apples = 4;
const bananas = 3;
console.log(`I have ${apples} apples`);
console.log(`I have ${apples + bananas} fruit`);
Die Ausgabe wird sein:
I have 4 apples
I have 7 fruit
Vorlagenliterale können auch für mehrzeilige Strings verwendet werden:
console.log(`This is the first line of text.
This is the second line of text.`);
Die Ausgabe wird sein:
This is the first line of text.
This is the second line of text.
Julia
apples = 4
bananas = 3
print("I have $apples apples and $bananas bananas, making $(apples + bananas) pieces of fruit in total.")
Die Ausgabe wird sein:
I have 4 apples and 3 bananas, making 7 pieces of fruit in total.
Kotlin
val quality = "superhero"
val apples = 4
val bananas = 3
val sentence = "A developer is a $quality. I have ${apples + bananas} fruit"
println(sentence)
Die Ausgabe wird sein:
A developer is a superhero. I have 7 fruit
Nemerle
def apples = 4;
def bananas = 3;
Console.WriteLine($"I have $apples apples.");
Console.WriteLine($"I have $(apples + bananas) fruit.");
Es unterstützt auch erweiterte Formatierungsfunktionen wie:
def fruit = ["apple", "banana"];
Console.WriteLine($<#I have ..$(fruit; "\n"; f => f + "s")#>);
Die Ausgabe wird sein:
apples
bananas
Shell der nächsten Generation
Die empfohlene Syntax wird ${expr}
jedoch $var
auch unterstützt:
quality = "superhero"
apples = 4
bananas = 3
sentence = "A developer is a $quality. I have ${apples + bananas} fruit"
echo(sentence)
Die Ausgabe wird sein:
A developer is a superhero. I have 7 fruit
Nim
Nim bietet String-Interpolation über das strutils-Modul. Formatierte String-Literale, die von Python F-String inspiriert sind, werden über das strformat-Modul bereitgestellt, das strformat-Makro überprüft, ob der Format-String wohlgeformt und typisiert ist, und werden dann zur Kompilierzeit in Nim-Quellcode erweitert.
import strutils, strformat
var apples = 4
var bananas = 3
echo "I have $1 apples".format(apples)
echo fmt"I have {apples} apples"
echo fmt"I have {apples + bananas} fruits"
# Multi-line
echo fmt"""
I have
{apples} apples"""
# Debug the formatting
echo fmt"I have {apples=} apples"
# Custom openChar and closeChar characters
echo fmt("I have (apples) {apples}", '(', ')')
# Backslash inside the formatted string literal
echo fmt"""{ "yep\nope" }"""
Die Ausgabe wird sein:
I have 4 apples
I have 4 apples
I have 7 fruits
I have
4 apples
I have apples=4 apples
I have 4 {apples}
yep
ope
Nix
let numberOfApples = "4";
in "I have ${numberOfApples} apples"
Die Ausgabe wird sein:
I have 4 apples
ParaSail
const Apples := 4
const Bananas := 3
Println ("I have `(Apples) apples.\n")
Println ("I have `(Apples+Bananas) fruit.\n")
Die Ausgabe wird sein:
I have 4 apples.
I have 7 fruit.
Perl
my $apples = 4;
my $bananas = 3;
print "I have $apples apples.\n";
print "I have @{[$apples+$bananas]} fruit.\n"; # Uses the Perl array (@) interpolation.
Die Ausgabe wird sein:
I have 4 apples.
I have 7 fruit.
PHP
<?php
$apples = 5;
$bananas = 3;
echo "There are $apples apples and $bananas bananas.";
echo "\n";
echo "I have {$apples} apples and {$bananas} bananas.";
Die Ausgabe wird sein:
There are 5 apples and 3 bananas.
I have 5 apples and 3 bananas.
Python
# in all versions
apples = 4
bananas = 3
print("I have %d apples and %d bananas" % (apples, bananas)) # no longer recommended
print("I have %(apples)d apples and %(bananas)d bananas" % locals()) # no longer recommended
# with Python 2.6+
print("I have {0} apples and {1} bananas".format(apples, bananas))
print("I have {a} apples and {b} bananas".format(b=bananas, a=apples))
# with Python 2.7+
print("I have {} apples and {} bananas".format(apples, bananas))
# or with Python 3.6+
print(f"I have {apples} apples and {bananas} bananas")
Die Ausgabe wird sein:
I have 4 apples and 3 bananas
Rubin / Kristall
apples = 4
puts "I have #{apples} apples"
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {a: apples}
Die Ausgabe wird sein:
I have 4 apples
Rost
Da es keine echten interpolierten Strings gibt, bietet Rust eine Problemumgehung über das std::fmt- Modul, das über verschiedene Makros wie format! , schreib! , und drucken! . Diese Makros werden zur Kompilierzeit in Rust-Quellcode umgewandelt, wobei jedes Argument mit einem Formatierer interagiert . Der Formatierer unterstützt Positionsparameter , benannte Parameter , Argumenttypen und das Definieren verschiedener Formatierungsmerkmale .
let (apples, bananas) = (4, 3);
println!("There are {} apples and {} bananas.", apples, bananas);
Die Ausgabe wird sein:
There are 4 apples and 3 bananas.
Scala
Scala 2.10+ hat die folgenden String-Interpolatoren implementiert: s, f und raw. Es ist auch möglich, benutzerdefinierte zu schreiben oder die Standardeinstellungen zu überschreiben.
Der Interpolator f ist ein Compilermakro, das eine Formatzeichenfolge mit eingebetteten Ausdrücken als Aufruf von String.format umschreibt. Es überprüft, ob die Formatzeichenfolge wohlgeformt und typisiert ist.
Die Standard-Interpolatoren
Die String-Interpolation von Scala 2.10+ ermöglicht das Einbetten von Variablenreferenzen direkt in verarbeitete String-Literale. Hier ist ein Beispiel:
val apples = 4
val bananas = 3
//before Scala 2.10
printf("I have %d apples\n", apples)
println("I have %d apples" format apples)
//Scala 2.10+
println(s"I have $apples apples")
println(s"I have ${apples + bananas} fruits")
println(f"I have $apples%d apples")
Die Ausgabe wird sein:
I have 4 apples
Sciter (Tiskript)
In Sciter wird jede Funktion, deren Name bei $ beginnt, als Interpolationsfunktion betrachtet, und daher ist die Interpolation anpassbar und kontextsensitiv:
var apples = 4
var bananas = 3
var domElement = ...;
domElement.$content(<p>I have {apples} apples</p>);
domElement.$append(<p>I have {apples + bananas} fruits</p>);
Wo
domElement.$content(<p>I have {apples} apples</p>);
wird dazu kompiliert:
domElement.html = "<p>I have " + apples.toHtmlString() + " apples</p>";
Snobol
apples = 4 ; bananas = 3
Output = "I have " apples " apples."
Output = "I have " (apples + bananas) " fruit."
Die Ausgabe wird sein:
I have 4 apples.
I have 7 fruit.
Schnell
In Swift kann ein neuer String-Wert aus einer Mischung aus Konstanten, Variablen, Literalen und Ausdrücken erstellt werden, indem deren Werte in ein String-Literal aufgenommen werden. Jedes in das Zeichenfolgenliteral eingefügte Element wird in ein Paar Klammern eingeschlossen, denen ein umgekehrter Schrägstrich vorangestellt ist.
let apples = 4
print("I have \(apples) apples")
Die Ausgabe wird sein:
I have 4 apples
Tcl
Die Tool Command Language hat immer die String-Interpolation in allen durch Anführungszeichen getrennten Strings unterstützt.
set apples 4
puts "I have $apples apples."
Die Ausgabe wird sein:
I have 4 apples.
Um die Werte tatsächlich zu formatieren – und nicht nur zu ersetzen – gibt es eine Formatierungsfunktion.
set apples 4
puts [format "I have %d apples." $apples]
Typoskript
Ab Version 1.4 unterstützt TypeScript die String-Interpolation mit Backticks ``
. Hier ist ein Beispiel:
var apples: number = 4;
console.log(`I have ${apples} apples`);
Die Ausgabe wird sein:
I have 4 apples
Die console.log
Funktion kann als printf
Funktion verwendet werden. Das obige Beispiel kann so umgeschrieben werden:
var apples: number = 4;
console.log("I have %d apples", apples);
Die Ausgabe bleibt gleich.
Visual Basic
Ab Visual Basic 14 wird die Zeichenfolgeninterpolation in Visual Basic unterstützt.
name = "Tom"
Console.WriteLine($"Hello, {name}")
druckt "Hallo, Tom".
Siehe auch
- Verkettung
- Unsachgemäße Eingabevalidierung
- printf-Formatzeichenfolge
- Quasi-Zitat
- String-Literal
- Auswechslung