string.Format Use
This page was last reviewed on Feb 20, 2023.
Dot Net Perls
String.Format. With formatting, we change how data appears. The C# string.Format method helps—we use it to change how numbers are printed with format codes.
Format notes. We can place other text inside the formatting string to compose the entire result string. We can even change numbers to percentages.
String Interpolation
First example. We use string.Format to combine 3 strings with formatting options. The first argument is the format string—it is a string literal.
Part 1 The program formats 3 variables. These are a string, an int and a DateTime struct.
Part 2 The 0, 1 and 2 are where the first, second and third arguments are inserted. A format specification comes after the ":" char.
Part 3 The string has formatting applied. The int is displayed with a decimal place. The year is displayed with 4 digits.
using System; // Part 1: variables. string value1 = "cat"; int value2 = 10000; DateTime value3 = new DateTime(2015, 11, 1); // Part 2: use string.Format method with markers. string result = string.Format("{0}: {1:0.0} - {2:yyyy}", value1, value2, value3); // Part 3: write the result. Console.WriteLine(result);
cat: 10000.0 - 2015
Number formats. We can specify that a value (like a double) can be formatted inside string.Format. A format string is the first argument to string.Format.
Note The format string uses the "0:0.0%" syntax. This means that the second argument is formatted with the pattern "0.0%."
Detail The "0.0%" part specifies the number of digits. We can have many digits before the decimal place, but only one after it.
using System; class Program { static void Main() { // Format a ratio as a percentage string. // ... You must specify the percentage symbol. // ... It will multiply the value by 100. double ratio = 0.73; string result = string.Format("string = {0:0.0%}", ratio); Console.WriteLine(result); } }
string = 73.0%
Padding. This can be expressed declaratively in format strings. Padding inserts characters at the left or right of the string to reach a specified length.
Tip Instead of the PadLeft and PadRight methods, you can use the string.Format method with special substitutions.
String PadRight, PadLeft
Detail Use the comma char followed by the padding size. A negative number will add padding to the right (left-align).
Also You can use a positive padding size to add padding to the left. This will right-align the string.
using System; class Program { static void Main() { // The constant formatting string. // ... It specifies the padding. // ... A negative number means to left-align. // ... A positive number means to right-align. const string format = "{0,-10} {1,10}"; // Construct the strings. string line1 = string.Format(format, 100, 5); string line2 = string.Format(format, "Carrot", "Giraffe"); // Write the formatted strings. Console.WriteLine(line1); Console.WriteLine(line2); } }
100 5 Carrot Giraffe
ToString. Sometimes, you need to just format a single number, like an integer or long. In this case, you don't need to use string.Format. You can just use the ToString virtual method.
using System; class Program { static void Main() { int value = 123; string a = string.Format("{0:0000}", value); // Too complex. string b = value.ToString("0000"); // Simpler. Console.WriteLine(a); Console.WriteLine(b); } }
0123 0123
Console. Programs can use format strings directly inside the Console.Write and Console.WriteLine methods. We can call Console.WriteLine with the same arguments as string.Format.
using System; class Program { static void Main() { string left = "hello"; string right = "friend"; Console.WriteLine("{0}, {1}!", left, right); } }
hello, friend!
Hex is a number representation. We use format strings and the ToString method to convert ints to hex format. The int.Parse method can then be used to convert them back.
Detail X formats as hexadecimal. You can specify X and then a number (such as X8) to pad the output on the left side with zeros.
Tip You can use the NumberStyles.AllowHexSpecifier argument to make int.Parse handle hex numbers.
using System; using System.Globalization; class Program { static void Main() { int value1 = 10995; // Write number in hex format. Console.WriteLine("{0:x}", value1); Console.WriteLine("{0:x8}", value1); Console.WriteLine("{0:X}", value1); Console.WriteLine("{0:X8}", value1); // Convert to hex. string hex = value1.ToString("X8"); // Convert from hex to integer. int value2 = int.Parse(hex, NumberStyles.AllowHexSpecifier); Console.WriteLine(value1 == value2); } }
2af3 00002af3 2AF3 00002AF3 True
FormatException. How can we solve this problem? System.FormatException is thrown by methods that receive format strings and substitutions.
{0} {1} {2}
FormatException, continued. Format strings use substitution markers. The arguments after the format string are placed in those markers in the same order.
Here The System.FormatException is thrown because the {2} substitution marker was not found in the argument list.
Tip To fix the program, we could remove the substitution marker {2} or add 2 more arguments.
Tip 2 Whenever we encounter a FormatException, it is worthwhile to check substitution markers and argument lists for formatting methods.
using System; class Program { static void Main() { Console.WriteLine("{0} {2}", "x"); } }
Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
String interpolation. For simple format strings, we can use string interpolation instead of the string.Format method. This has clearer syntax that is validated by the compiler.
using System; class Program { static void Main() { int value = 100; // String interpolation can be used instead of a format string. Console.WriteLine($"The size is {value}."); } }
The size is 100.
StringBuilder. This class has a method called AppendFormat. The AppendFormat method receives a formatting string and the arguments to the formatting string.
StringBuilder AppendFormat
using System; using System.Text; class Program { static void Main() { var builder = new StringBuilder(); // Use AppendFormat on StringBuilder. builder.AppendFormat("{0} and {1}", "cat", "dog"); Console.WriteLine(builder); } }
cat and dog
DateTime. When developing C# programs, we often need to place dates and times in strings. We can use format strings for this task.
Note The string.Format method can be used with DateTime arguments. These will be inserted into the substitution markers.
DateTime Format
Note 2 Files often need to have file names that are based on some characteristic, like dates.
Filename, Date
A summary. With Format, we insert argument strings and separators together. We can specify display options for each argument. We combined strings and dates and numbers.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 20, 2023 (edit).
© 2007-2024 Sam Allen.