static void Main()
{
//
// Declare three variables that we will use in the format method.
// ... The values they have are not important.
//
string value1 = "This is test";
int value2 = 530;
DateTime value3 = new DateTime(2011, 11, 11);
//
// Use string.Format method with four arguments.
// ... The first argument is the formatting string.
// ... It specifies how the next three arguments are formatted.
//
string result = string.Format("{0}: {1:0.0} - {2:yyyy}",value1,value2,value3);
Console.WriteLine(result);
}
/*
OUTPUT
This is test: 530.0 - 2011
*/
static void Main()
{
//
// Format a ratio as a percentage string.
// ... You must specify the percentage symbol in the format string.
// ... It will multiply the value by 100 for you.
//
double ratio = 0.530;
string result = string.Format("string = {0:0.0%}",ratio);
Console.WriteLine(result);
}
/*
OUTPUT
string = 530.0%
*/
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");
Console.WriteLine(line1);
Console.WriteLine(line2);
}
/*
OUTPUT
100 5
Carrot Giraffe
*/
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
*/
static void Main()
{
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format)); // Write to console
}
/*
OUTPUT
Feb Fri 27 11:41 2009
*/
Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/DUa-Zy493Oo/14175