In C#, String.Format() method is generally used to insert variable, expression or value of an object into another string variable. It is a static method of String class and takes a input string that identifies replaceable parameters by using numbers in curly braces.
For example : String.Format("My name is : {0}", name);
The simplest form of String.Format method to format objects and variables is as follows.
1 |
public static string Format (string format, object? arg); |
- string format (Input parameter) : Its the input string consists of fixed text intermixed with indexed placeholders, i.e curly braces, that correspond to the objects in the list.
- object? arg (Input parameter) : The object to be used for formatting.
Example of String.Format() in C# :
In below example, we insert the string name = "James"; to another string "My Name is : {0}" in {0} index . The result string becomes as “My Name is James”.
1 2 3 |
string name = "James"; string strFormat = String.Format("My name is : {0}", name); Console.WriteLine(strFormat);//My name is James |
Example of inserting multiple item in to String.Format() in C# :
In below example, we are inserting a string value and an integer value into another string using String.Format method.
1 2 3 4 |
int age = 25; string name = "James"; string strFormat = String.Format("{0} is {1} years old", name, age); Console.WriteLine(strFormat); //James is 25 years old |
In above, string string strFormat = String.Format("{0} is {1} years old", name, age); tells the Format method to replace {0} with first parameter value “James“ , and replace {1} with the second parameter value “25”. The resultant string becomes as “James is 25 years old“ .
Example of inserting an object in to String.Format() in C# :
In below example, we have created a Student class and in Main method we are inserting Student property values in to another string using String.Format method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; namespace StringTypeDemo { class Program { static void Main(string[] args) { Student stu = new Student(); stu.FirstName = "James"; stu.LastName = "Cameron"; stu.EnrollmentDate = new DateTime(2019, 04, 12); string str = string.Format("{0} {1} Enrollment Date is on : {2}", stu.FirstName, stu.LastName, stu.EnrollmentDate.ToString("MM/dd/yyyy")); Console.WriteLine(str); //James Cameron Enrollment Date is on : 04-12-2019 } } class Student { public string FirstName { get; set; } public string LastName { get; set; } public DateTime EnrollmentDate { get; set; } } } |
So in the {0} index it inserted stu.FirstName as “James“, in the {1} index it inserted stu.LastName as “Cameron” and in the {2} index , it inserted stu.EnrollmentDate.ToString("MM/dd/yyyy") value as “04-12-2019“.
When you run above example, then it prints “James Cameron Enrollment Date is on : 04-12-2019” as the final string.
Formatting of a string using String.Format() in C# :
We can also format the object using control formatting syntax inside Format method. It uses below syntax for formatting an object.
{index number : formatting expression}
- index number : The zero-based index of the argument, it would be replaced with the string representation at this position, if the argument is null then empty string will be replaced.
- formatting expression : It is the formatting expression of the result string out put.
For example, in below code we have applied formatting information as {2:D} for the index number 2 parameter stu.EnrollmentDate
1 2 3 4 5 6 7 8 |
Student stu = new Student(); stu.FirstName = "James"; stu.LastName = "Cameron"; stu.EnrollmentDate = new DateTime(2019, 04, 12); string str = string.Format("{0} {1} Enrollment Date is on : {2:D}", stu.FirstName, stu.LastName, stu.EnrollmentDate); Console.WriteLine(str); //James Cameron Enrollment Date is on : 12 April 2019 |
When we run above sample code, then it formats the stu.EnrollmentDate value to “12 April 2019“. The final output thus becomes “James Cameron Enrollment Date is on : 12 April 2019“ .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; namespace StringTypeDemo { class Program { static void Main(string[] args) { decimal decimalVal = 16309.5436m; double doubleVal = 123; DateTime dt = new DateTime(2019, 04, 12); string formatDecimal = String.Format("Formated Decimal value : {0:0,000.00}", decimalVal); string formatDoubleVal = String.Format("Formatted Double value : {0:0.00}", doubleVal); string formatDt= String.Format("Formated Datetime value : {0:d}", DateTime.Now, DateTime.Now); Console.WriteLine(formatDecimal); Console.WriteLine(formatDoubleVal); Console.WriteLine(formatDt); } } } |
When we run above code, then it generates below output.
To check more formatting type and option, please visit Format types in .NET
Alignment using String.Format() in C# :
Along with formatting the object value, we can also do alignment and add spacing to it. You can define the width of the string that is inserted into the result string.
It uses syntax such as {0,10} , that means it will inserts 10-character string in to the result string value. Following is the syntax and different conditions of adding spaces to object using String.Format method.
{index number , alignment value}
- alignment value : A signed integer value, that defines the width of string that is going to be inserted to the result string. To left-align strings in a field, you have to provide negative value, such as {0,-10} and to right-aligned, you have to provide a positive value, such as {0,10}
We can also include formatting string along with the alignment value to the expression as follows.
{index number , alignment value : formatting expression}
Lets look at below example to understand how this alignment and formatting expression works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; namespace StringTypeDemo { class Program { static void Main(string[] args) { DateTime tempDate = new DateTime(2020, 10, 28, 6, 0, 0); decimal[] temps = { 70.452m, 65.98m, 71.6m, 74.1m, 72.156m, 72.228m }; Console.WriteLine("Left Alighnment"); Console.WriteLine("*****************************************"); Console.WriteLine("{0,-20} {1,-15}\n", "Date", "Temperature"); for (int i = 0; i < temps.Length; i++) { string leftAlignString = String.Format("{0,-20:g} {1,-15:N1}", tempDate.AddDays(i), temps[i]); Console.WriteLine(leftAlignString); } Console.WriteLine("\n"); Console.WriteLine("Right Alighnment"); Console.WriteLine("*****************************************"); Console.WriteLine("{0,20} {1,15}\n", "Date", "Temperature"); for (int j = 0; j < temps.Length; j++) { string rightAlignString = String.Format("{0,20:g} {1,15:N1}", tempDate.AddDays(j), temps[j]); Console.WriteLine(rightAlignString); } } } } |
When we run above program then it generates below output.
If you look at the output, then you can find that we have implemented.
- Left alignment by using {0,-20} {1,-15} for both first and second argument.
- Right alignment by using {0,20} {1,15} for both arguments.
- The formatting expression {0,-20:g} {1,-15:N1} and {0,20:g} {1,15:N1} to format the result string.
Thanks for visiting, Please provide your feedback and do check my other articles.