TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# String Format

Insert values into a string with string.Format. Specify percentages, decimals and padding.
String.Format. Among the distant rocks you see a sparkle of light. You discover a mysterious tablet with an ancient message upon it. But it is formatted strangely. You cannot read it.
With formatting, we change how data appears. The string.Format method helps. We use it to change how numbers are printed. We use format codes.
First, we use string.Format to combine 3 strings with formatting options. The format string itself is the first argument. It is usually specified as a string literal.

Markers: The 0, 1 and 2 are where the first, second and third arguments are inserted. A format specification comes after the ":" char.

Variables: The program formats 3 variables. These are a string, an int and a DateTime struct.

Result: The string has formatting applied. The int is displayed with a decimal place. The year is displayed with 4 digits.

C# program that uses string.Format using System; class Program { static void Main() { // Declare three variables. // ... The values they have are not important. string value1 = "The Dev Codes"; int value2 = 10000; DateTime value3 = new DateTime(2015, 11, 1); // Use string.Format method with four arguments. // ... The first argument is the formatting string. // ... It specifies how the next arguments are formatted. string result = string.Format("{0}: {1:0.0} - {2:yyyy}", value1, value2, value3); // Write the result. Console.WriteLine(result); } } Output The Dev Codes: 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 in this example uses the 0:0.0% syntax. This means that the second argument is formatted with the pattern 0.0%.

Digits: The "0.0%" part specifies the number of digits. We can have many digits before the decimal place, but only one after it.

Quote: The presence of a "%" character in a format string causes a number to be multiplied by 100 before it is formatted.

Custom Numeric Format Strings: microsoft.com
C# program that uses string.Format with number 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); } } Output 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.

PadRight, PadLeft

Sizes: 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.

C# program that uses string.Format for padding 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); } } Output 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.ToString
C# program that uses string.Format and ToString 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); } } Output 0123 0123
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.

Code: 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.

C# program that handles hex number conversions 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); } } Output 2af3 00002af3 2AF3 00002AF3 True
FormatException. How can we solve this problem? System.FormatException is thrown by methods that receive format strings and substitutions.
Substitution markers: {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.

C# program that throws an exception using System; class Program { static void Main() { Console.WriteLine("{0} {2}", "x"); } } Output Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Benchmark, ToString. When creating complex strings, we are tempted to use concatenations. But we can achieve better performance by unifying the string operations.

Here: We look at a program that compares 2 methods of creating a formatted string.

Version 1: The Method1 version of the logic uses a single format string. The MB part is inside the format string.

Version 2: This version uses a format string and then another concatenation after that.

Result: Method1 is faster. With string.Format and ToString, we can combine literal concatenations in the format for better performance.

C# program that times ToString method, format string using System; using System.Diagnostics; class Program { static string Method1() { return 100.ToString("0.0 MB"); } static string Method2() { return 100.ToString("0.0") + " MB"; } const int _max = 1000000; static void Main() { var s1 = Stopwatch.StartNew(); // Version 1: use a format string to create the complete string. for (int i = 0; i < _max; i++) { Method1(); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use a format string and then concatenate. for (int i = 0; i < _max; i++) { Method2(); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); } } Output 228.05 ns Format string 241.35 ns Format string and concat
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.String Interpolation
C# program that uses string interpolation 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}."); } } Output The size is 100.
Dates. DateTime, a struct, represents any possible date and time. The string.Format method can be used with DateTime arguments. These will be inserted into the substitution markers.DateTime, Format
File names. Many programs need to create files dynamically. The files often need to have file names that are based on some characteristic.

For example: A logging file can have a file name that is based on the exact date and time it was written.

Tip: You can use the string.Format method with substitutions to create the file names based on state variables.

Filename, DateTime
StringBuilder. This class has a method called AppendFormat. The AppendFormat method receives a formatting string and the arguments to the formatting string.AppendFormat
Console. Programs can use format strings directly inside the Console.Write and Console.WriteLine methods. In Visual Studio, type Console.WriteLine. Scroll through the IntelliSense window.Console

Then: You can call Console.WriteLine with the same arguments as the string.Format method receives. It will call string.Format.

Internals. The string.Format method is implemented with a params argument—this is a variable parameter list. This results in an array allocation on each invocation of the method.Params
Internals, substitution processing. String.Format uses StringBuilder, which contains a mutable character buffer. It estimates a capacity based on a heuristic.StringBuilder Capacity
Internals, AppendFormat. We find the AppendFormat method is called to process the substitutions themselves. The ToString method is called. It does not normally require a copy to be made.StringBuilder ToString
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf