In this post we’ll learn about the C# | String Format() method with the help of a detailed examples. The Format() method returns a formatted string based on the argument passed.
Important points of String.Format() method:
- It is used to format the string output. (Refer below example)
- It a static method and we have used the by class name
String
to call it.
Syntex:
String.Format(String format, Object...args);
Example: in Below example we have taken string format example. First parameter is main in which we have “Welcome to {0} {1}“. It means next two parameters will get replaced at {0} and {1} position respectively. Let’s see how it will work.
- We have two format items
{0}
and{1}
- “Code Config” which is first parameter’s text, and it will come at {0}
- “website” which is second parameter’s text and will come at {1}.
static void Main(string[] args)
{
string name = "Code Config";
// format string as below
string FormatedOutput = String.Format("Welcome to {0} {1}", "Code Config", "website");
Console.WriteLine(FormatedOutput);
Console.ReadLine();
}

String Format for Int in C#
Integer numbers can be formatted in .NET in many ways. Below example show how to align numbers with spaces or zeroes.
Add zeroes before int number in C#
String.Format("{0:00000}", 21); // "00021"
String.Format("{0:00000}", -21); // "-00021"
Align number to the right or left in C#
String.Format("{0,5}", 21); // " 21"
String.Format("{0,-5}", 21); // "21 "
String.Format("{0,5:000}", 21); // " 021"
String.Format("{0,-5:000}", 21); // "021 "
Visit our website’s C# Section for more such posts.