There are two principal mechanisms for formatting strings in C#/.NET. Use of String.Format()
and string interpolation.
String.Format()
takes a string (referred to in the documentation as a composite format) comprising fixed text and placeholders (known in the documentation as format items), and a variable number of arguments. The return value resolves each format item using the corresponding argument and combines the resolved values with the fixed text.
string.Format("I had {0} bitcoins on {1}, the day I forgot my password.", 55.5, new DateTime(2010, 2, 25));
// => "I had 55.5 bitcoins on 2/25/2010 00:00:00, the day I forgot my password." - US settings
This mechanism is technically known as composite formatting.
Interpolated strings are prefixed with a $
and include run-time expressions enclosed in braces. The format item has the following syntax: $"{<interpolationExpression>}"
. They do away with the need for a separate list of arguments. The result is functionally equivalent to the String.Format()
mechanism.
var loadsOf = 55.5;
var thatDay = new DateTime(2010, 2, 25);
$"I had {loadsOf} bitcoins on {thatDay}, the day I forgot my password."
// => "I had 55.5 bitcoins on 2/25/2010 00:00:00, the day I forgot my password." - US settings
The text in braces, placeholders in the case of the composite format and interpolated expressions in the case of string interpolation is known as a format item.
A format item can comprise up to 3 parts. The first is the mandatory expression or argument placeholder as seen in the example code above. In addition, there is an optional alignment (introduced with a comma, ",") and an optional format string (introduced with a colon ":").
{<interpolationExpression>[,<alignment>][:<formatString>]}
The alignment specifies the length of the "field" in which the text is placed, padded to the left with spaces if the alignment is positive or to the right if it is negative.
The format string specifies the shape of the text output such as whether thousands separators should be included for a number or whether the date part only of a DateTime
object should be output.
The following code illustrates display of the data portion of a DateTime
object and a floating-point number in exponential form.
var loadsOf = 55.5;
var thatDay = new DateTime(2010, 2, 25);
$"I had {loadsOf:E} bitcoins on {thatDay:d}, the day I forgot my password."
// => I had 5.550000E+001 bitcoins on 02/25/2010, the day I forgot my password. - US settings
string.Format(
"I had {0:E} bitcoins on {1:d}, the day I forgot my password.",
loadsOf, thatDay)
// => I had 5.550000E+001 bitcoins on 02/25/2010, the day I forgot my password. - US settings
There are both standard and custom formatting for both numbers and dates. There is no vital difference between custom and standard except that you have a chance to compose custom format strings out of format letters.
Each thread has a default culture Thread.CurrentThread.CurrentCulture
encapsulated in an instance of CultureInfo
. The thread's culture determines how dates and numbers are formatted with respect to regional variations such as the difference in conventional date format between the UK DD/MM/YYYY and the US MM/DD/YYYY.
CultureInfo
implements the IFormatProvider
interface which can be passed to certain overloads of String.Format()
. This can be used to override the thread culture.
Verbatim strings allow multi-line strings. They are introduced with an @.
string str = @"
See no wretched
quotes everywhere
";
In this exercise, you are going to help high school sweethearts profess their love on social media.
Please implement the static HighSchoolSweethearts.DisplaySingleLine()
method to take two names and display them separated by a heart.
The formatted text should be 61 characters wide, with the heart in the center of the string.
All names are guaranteed to fit well within the width of the line.
HighSchoolSweethearts.DisplaySingleLine("Lance Green", "Pat Riley");
// => " Lance Green β‘ Pat Riley "
Implement the static HighSchoolSweethearts.DisplayBanner()
method which displays the two sets of initials separated with a plus sign.
HighSchoolSweethearts.DisplayBanner("L. G.", "P. R.");
// see the ascii art below
****** ******
** ** ** **
** ** ** **
** * **
** **
** L. G. + P. R. **
** **
** **
** **
** **
** **
** **
***
*
Implement the static HighSchoolSweethearts.DisplayGermanExchangeStudents()
method to show date of start of relationship and length of time for our german exchange students.
HighSchoolSweethearts.DisplayGermanExchangeStudents("Norbert", "Heidi", new DateTime(2019, 1, 22), 1535.22f);
// => "Norbert and Heidi have been dating since 22.01.2019 - that's 1.535,22 hours"
Sign up to Exercism to learn and master C# with 62 concepts, 167 exercises, and real human mentoring, all for free.