format strings in your C# program using the string.Format method & custom format specifications. The string.Format method is a static method that receives a string that specifies where the following parameters should be inserted, & these are called substitutions. The method is used in plenty of places in the .NET Framework. Solution. Here they look at examples of the string.Format method in the C# language & then peek at other places in the framework where it's used, & finally explore its implementation.
Formatting multiple strings
This example demonstrates the use of the string.Format method to combine three strings with formatting options. The resulting string contains separators between the parameter strings. The format string itself is the first parameter to the string.Format method and it is specified as a string literal. The position markers in the format string are specified to the left of the colons, and this means the "0", "1:", and "2:" indicate where the first, second, and third parameters are inserted. The part after the colons and in between the { } brackets indicates the exact format specification for that variable.
Program that uses string.Format with three variables (C#)
using System;
class Program
{
static void Main()
{
//
// Declare three variables that we will use in the format method.
// ... The values they have are not important.
//
string value1 = "Dot Net Perls";
int value2 = 10000;
DateTime value3 = new DateTime(2007, 11, 1);
//
// Use string.Format method with four parameters.
// ... The first parameter is the formatting string.
// ... It specifies how the next three parameters are formatted.
//
string result = string.Format("{0}: {1:0.0} - {2:yyyy}",
value1,
value2,
value3);
//
// Write the result.
//
Console.WriteLine(result);
}
}
0 comments:
Post a Comment