411 REFERENCE · Wikibooks
Programming Fundamentals/String Formatting
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Overview
String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.Wikipedia: String interpolation
Discussion
Most current programming languages provide one or more string formatting functions that use a template string with placeholders and optional alignment, width, and precision indicators to generate formatted output.
LanguageFunctionExamplesC++snprintf()snprintf(str, sizeof(str), "Hello %s!", name);snprintf(str, sizeof(str), "$%.2f", value);C#Format()String.Format("Hello {0}!", name);String.Format("{0:$0.00}", value);Javaformat()String.format("Hello %s!", name);String.format("$%.2f", value);JavaScripttemplate literal`Hello ${name}`;`$${value.toFixed(2)}`;Pythonformat()"Hello {}!".format(name)"${:.2f}".format(value)SwiftinterpolationString()"Hello \(name)!"String(format:"%.2f", value)
String interpolation, like string concatenation, may lead to security problems. If user input data is improperly escaped or filtered, the system may be exposed to code injection.Wikipedia: String interpolation
Key Terms
code injection
The exploitation of a computer bug that is caused by processing invalid data.Wikipedia: Code injection
formatting
Modifying the way the output is displayed.
interpolation
Variable substitution
string interpolation
Evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
References
cnx.org: Programming Fundamentals – A Modular Structured Approach using C++