The String.Format()
method in C# is used to format a string. This method takes a format string and an object array as parameters and formats the string accordingly. The format string contains placeholders for the objects in the object array.
For example, if we have a string "{0} is a {1}" and an object array containing two strings, "John" and "programmer", the String.Format()
method will return the string "John is a programmer".
This method is often used to format user-input data before it is displayed or stored. For instance, if we have a text box for users to input their date of birth, we can use the String.Format()
method to format the data into a more readable format before displaying it or storing it in a database.
The syntax of the String.Format()
method is as follows:
public static string Format(string format, params object[] args)
The String.Format()
method takes the following parameters:
format
: This is the format string.args
: This is an object array containing the objects to be formatted.The String.Format()
method returns a string containing the formatted objects.
Let's take a look at a simple example to see how the String.Format()
method works. In this example, we have a string containing placeholders for two objects. We also have an object array containing two strings. The String.Format()
method formats the string, using the objects in the object array.
using System;class HelloWorld{static void Main(){string str = "Hello, {0}! Welcome to {1}.";object[] args = new object[] {"John", "Educative"};string formattedStr = String.Format(str, args);Console.WriteLine(formattedStr);}}
In the code above:
{0}
and {1}
."John"
and "Educative"
. String.Format()
method.