Επεξεργασία

Κοινή χρήση μέσω


String.Format Method

Definition

Converts the value of objects to strings based on the formats specified and inserts them into another string.

If you are new to the String.Format method, see Get started with the String.Format method for a quick overview.

Overloads

Format(IFormatProvider, String, Object[])

Replaces the format items in a string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object, Object, Object)

Replaces the format items in a string with the string representation of three specified objects. An parameter supplies culture-specific formatting information.

Format(String, Object, Object, Object)

Replaces the format items in a string with the string representation of three specified objects.

Format(IFormatProvider, String, Object, Object)

Replaces the format items in a string with the string representation of two specified objects. A parameter supplies culture-specific formatting information.

Format(String, Object, Object)

Replaces the format items in a string with the string representation of two specified objects.

Format(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

Format(IFormatProvider, String, Object)

Replaces the format item or items in a specified string with the string representation of the corresponding object. A parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, ReadOnlySpan<Object>)

Replaces the format items in a string with the string representations of corresponding objects in a specified span. A parameter supplies culture-specific formatting information.

Format(String, ReadOnlySpan<Object>)

Replaces the format item in a specified string with the string representation of a corresponding object in a specified span.

Format(String, Object[])

Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

Format(String, Object)

Replaces one or more format items in a string with the string representation of a specified object.

Format(IFormatProvider, CompositeFormat, Object[])

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

Format<TArg0,TArg1,TArg2>(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

Format<TArg0,TArg1>(IFormatProvider, CompositeFormat, TArg0, TArg1)

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

Format<TArg0>(IFormatProvider, CompositeFormat, TArg0)

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

Remarks

For more information about this API, see Supplemental API remarks for String.Format.

Format(IFormatProvider, String, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format items in a string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider provider, string format, params object[] args);
public static string Format (IFormatProvider? provider, string format, params object?[] args);
static member Format : IFormatProvider * string * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As String, ParamArray args As Object()) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

args
Object[]

An object array that contains zero or more objects to format.

Returns

A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

Exceptions

format or args is null.

format is invalid.

-or-

The index of a format item is less than zero, or greater than or equal to the length of the args array.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert four or more expressions to their string representations and to embed those representations in a string. In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. If these methods don't exist, it calls the object's parameterless ToString method.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Example: Culture-sensitive formatting

This example uses the Format(IFormatProvider, String, Object[]) method to display the string representation of some date and time values and numeric values by using several different cultures.

string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };

DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
double value = 9164.32;

Console.WriteLine("Culture     Date                                Value\n");
foreach (string cultureName in cultureNames)
{
   System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
   string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", 
                                 culture.Name, dateToDisplay, value);
   Console.WriteLine(output);
}    
// The example displays the following output:
//    Culture     Date                                Value
//    
//    en-US       Tuesday, September 01, 2009         9,164.32
//    fr-FR       mardi 1 septembre 2009              9 164,32
//    de-DE       Dienstag, 1. September 2009         9.164,32
//    es-ES       martes, 01 de septiembre de 2009    9.164,32
open System
open System.Globalization

let cultureNames = [| "en-US"; "fr-FR"; "de-DE"; "es-ES" |]

let dateToDisplay = DateTime(2009, 9, 1, 18, 32, 0)
let value = 9164.32

printfn "Culture     Date                                Value\n"
for cultureName in cultureNames do
    let culture = CultureInfo cultureName
    String.Format(culture, "{0,-11} {1,-35:D} {2:N}", culture.Name, dateToDisplay, value)
    |> printfn "%s"
// The example displays the following output:
//    Culture     Date                                Value
//    
//    en-US       Tuesday, September 01, 2009         9,164.32
//    fr-FR       mardi 1 septembre 2009              9 164,32
//    de-DE       Dienstag, 1. September 2009         9.164,32
//    es-ES       martes, 01 de septiembre de 2009    9.164,32
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR", "de-DE", "es-ES" }
      
      Dim dateToDisplay As Date = #9/1/2009 6:32PM#
      Dim value As Double = 9164.32

      Console.WriteLine("Culture     Date                                Value")
      Console.WriteLine()      
      For Each cultureName As String In cultureNames
         Dim culture As New CultureInfo(cultureName)
         Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
                                              culture.Name, dateToDisplay, value)
         Console.WriteLine(output)
      Next    
   End Sub
End Module
' The example displays the following output:
'       Culture     Date                                Value
'       
'       en-US       Tuesday, September 01, 2009         9,164.32
'       fr-FR       mardi 1 septembre 2009              9 164,32
'       de-DE       Dienstag, 1. September 2009         9.164,32
'       es-ES       martes, 01 de septiembre de 2009    9.164,32

See also

Applies to

Format(IFormatProvider, String, Object, Object, Object)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format items in a string with the string representation of three specified objects. An parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2);
static member Format : IFormatProvider * string * obj * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

arg0
Object

The first object to format.

arg1
Object

The second object to format.

arg2
Object

The third object to format.

Returns

A copy of format in which the format items have been replaced by the string representations of arg0, arg1, and arg2.

Exceptions

format is null.

format is invalid.

-or-

The index of a format item is less than zero, or greater than two.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert three expressions to their string representations and to embed those representations in a string. In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. If these methods don't exist, it calls the object's parameterless ToString method.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Applies to

Format(String, Object, Object, Object)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format items in a string with the string representation of three specified objects.

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (string format, object arg0, object arg1, object arg2);
public static string Format (string format, object? arg0, object? arg1, object? arg2);
static member Format : string * obj * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String

Parameters

arg0
Object

The first object to format.

arg1
Object

The second object to format.

arg2
Object

The third object to format.

Returns

A copy of format in which the format items have been replaced by the string representations of arg0, arg1, and arg2.

Exceptions

format is null.

format is invalid.

-or-

The index of a format item is less than zero, or greater than two.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert the value of three expressions to their string representations and to embed those representations in a string.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Example: Format three arguments

This example uses the Format(String, Object, Object, Object) method to create a string that illustrates the result of a Boolean And operation with two integer values. Note that the format string includes six format items, but the method has only three items in its parameter list, because each item is formatted in two different ways.

using namespace System;

void main()
{
   String^ formatString = "    {0,10} ({0,8:X8})\n" + 
                           "And {1,10} ({1,8:X8})\n" + 
                           "  = {2,10} ({2,8:X8})";
   int value1 = 16932;
   int value2 = 15421;
   String^ result = String::Format(formatString, 
                                   value1, value2, value1 & value2);
   Console::WriteLine(result);
}
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
string formatString = "    {0,10} ({0,8:X8})\n" + 
                      "And {1,10} ({1,8:X8})\n" + 
                      "  = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
string result = String.Format(formatString, 
                              value1, value2, value1 & value2);
Console.WriteLine(result);
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
open System

let formatString = 
    "    {0,10} ({0,8:X8})\nAnd {1,10} ({1,8:X8})\n  = {2,10} ({2,8:X8})"

let value1 = 16932
let value2 = 15421
String.Format(formatString, value1, value2, value1 &&& value2)
|> printfn "%s"
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
Public Module Example
   Public Sub Main()
      Dim formatString As String = "    {0,10} ({0,8:X8})" + vbCrLf +  _
                                   "And {1,10} ({1,8:X8})" + vbCrLf + _
                                   "  = {2,10} ({2,8:X8})"
      Dim value1 As Integer = 16932
      Dim value2 As Integer = 15421
      Dim result As String = String.Format(formatString, _
                                           value1, value2, value1 And value2)
      Console.WriteLine(result)                          
   End Sub
End Module
' The example displays the following output:
'                16932 (00004224)
'       And      15421 (00003C3D)
'         =         36 (00000024)

See also

Applies to

Format(IFormatProvider, String, Object, Object)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format items in a string with the string representation of two specified objects. A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1);
static member Format : IFormatProvider * string * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

arg0
Object

The first object to format.

arg1
Object

The second object to format.

Returns

A copy of format in which format items are replaced by the string representations of arg0 and arg1.

Exceptions

format is null.

format is invalid.

-or-

The index of a format item is not zero or one.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert two expressions to their string representations and to embed those representations in a string. In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. If these methods don't exist, it calls the object's parameterless ToString method.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Applies to

Format(String, Object, Object)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format items in a string with the string representation of two specified objects.

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (string format, object arg0, object arg1);
public static string Format (string format, object? arg0, object? arg1);
static member Format : string * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object) As String

Parameters

arg0
Object

The first object to format.

arg1
Object

The second object to format.

Returns

A copy of format in which format items are replaced by the string representations of arg0 and arg1.

Exceptions

format is null.

format is invalid.

-or-

The index of a format item is not zero or one.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert the value of two expressions to their string representations and to embed those representations in a string.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Example: Format two arguments

This example uses the Format(String, Object, Object) method to display time and temperature data stored in a generic Dictionary<TKey,TValue> object. Note that the format string has three format items, although there are only two objects to format. This is because the first object in the list (a date and time value) is used by two format items: The first format item displays the time, and the second displays the date.

using namespace System;
using namespace System::Collections::Generic;

void main()
{
   Dictionary<DateTime, Double>^ temperatureInfo = gcnew Dictionary<DateTime, Double>(); 
   temperatureInfo->Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46);
   temperatureInfo->Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81);
      
   Console::WriteLine("Temperature Information:\n");
   String^ output;   
   for each (KeyValuePair<DateTime, Double>^ item in temperatureInfo)
   {
      output = String::Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}�F", 
                              item->Key, item->Value);
      Console::WriteLine(output);
   }
}
// The example displays the following output:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5�F
//       Temperature at 10:00 AM on 12/1/2010:  36.8�F
Dictionary<DateTime, Double> temperatureInfo = new Dictionary<DateTime, Double>(); 
temperatureInfo.Add(new DateTime(2010, 6, 1, 14, 0, 0), 87.46);
temperatureInfo.Add(new DateTime(2010, 12, 1, 10, 0, 0), 36.81);

Console.WriteLine("Temperature Information:\n");
string output;   
foreach (var item in temperatureInfo)
{
   output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", 
                          item.Key, item.Value);
   Console.WriteLine(output);
}
// The example displays output like the following:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5°F
//       Temperature at 10:00 AM on 12/1/2010:  36.8°F
open System
open System.Collections.Generic

let temperatureInfo = Dictionary<DateTime, float>() 
temperatureInfo.Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46)
temperatureInfo.Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81)

printfn $"Temperature Information:\n"
for item in temperatureInfo do
   String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", item.Key, item.Value)
   |> printfn "%s"
// The example displays output like the following:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5°F
//       Temperature at 10:00 AM on 12/1/2010:  36.8°F
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim temperatureInfo As New Dictionary(Of Date, Double) 
      temperatureInfo.Add(#6/1/2010 2:00PM#, 87.46)
      temperatureInfo.Add(#12/1/2010 10:00AM#, 36.81)
      
      Console.WriteLine("Temperature Information:")
      Console.WriteLine()
      Dim output As String   
      For Each item In temperatureInfo
         output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", _
                                item.Key, item.Value)
         Console.WriteLine(output)
      Next
   End Sub
End Module
' The example displays the following output:
'       Temperature Information:
'       
'       Temperature at  2:00 PM on  6/1/2010:  87.5°F
'       Temperature at 10:00 AM on 12/1/2010:  36.8°F

See also

Applies to

Format(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, ReadOnlySpan<System::Object ^> args);
public static string Format (IFormatProvider? provider, System.Text.CompositeFormat format, ReadOnlySpan<object?> args);
public static string Format (IFormatProvider? provider, System.Text.CompositeFormat format, scoped ReadOnlySpan<object?> args);
static member Format : IFormatProvider * System.Text.CompositeFormat * ReadOnlySpan<obj> -> string
Public Shared Function Format (provider As IFormatProvider, format As CompositeFormat, args As ReadOnlySpan(Of Object)) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

args
ReadOnlySpan<Object>

A span of objects to format.

Returns

The formatted string.

Exceptions

format is null.

The index of a format item is greater than or equal to the number of supplied arguments.

Applies to

Format(IFormatProvider, String, Object)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item or items in a specified string with the string representation of the corresponding object. A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public static string Format (IFormatProvider provider, string format, object arg0);
public static string Format (IFormatProvider? provider, string format, object? arg0);
static member Format : IFormatProvider * string * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

arg0
Object

The object to format.

Returns

A copy of format in which the format item or items have been replaced by the string representation of arg0.

Exceptions

format is null.

format is invalid.

-or-

The index of a format item is not zero.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert the value of an expression to its string representation and to embed that representation in a string. In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. The method converts arg0 to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. If these methods don't exist, it calls the object's parameterless ToString method.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Applies to

Format(IFormatProvider, String, ReadOnlySpan<Object>)

Replaces the format items in a string with the string representations of corresponding objects in a specified span. A parameter supplies culture-specific formatting information.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, ReadOnlySpan<System::Object ^> args);
public static string Format (IFormatProvider? provider, string format, scoped ReadOnlySpan<object?> args);
static member Format : IFormatProvider * string * ReadOnlySpan<obj> -> string
Public Shared Function Format (provider As IFormatProvider, format As String, args As ReadOnlySpan(Of Object)) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

args
ReadOnlySpan<Object>

An object span that contains zero or more objects to format.

Returns

A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

Applies to

Format(String, ReadOnlySpan<Object>)

Replaces the format item in a specified string with the string representation of a corresponding object in a specified span.

public:
 static System::String ^ Format(System::String ^ format, ReadOnlySpan<System::Object ^> args);
public static string Format (string format, scoped ReadOnlySpan<object?> args);
static member Format : string * ReadOnlySpan<obj> -> string
Public Shared Function Format (format As String, args As ReadOnlySpan(Of Object)) As String

Parameters

args
ReadOnlySpan<Object>

An object span that contains zero or more objects to format.

Returns

A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

Applies to

Format(String, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

public:
 static System::String ^ Format(System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (string format, params object[] args);
public static string Format (string format, params object?[] args);
static member Format : string * obj[] -> string
Public Shared Function Format (format As String, ParamArray args As Object()) As String

Parameters

args
Object[]

An object array that contains zero or more objects to format.

Returns

A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.

Exceptions

format or args is null.

format is invalid.

-or-

The index of a format item is less than zero, or greater than or equal to the length of the args array.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert the value of four or more expressions to their string representations and to embed those representations in a string. Since the args parameter is marked with the System.ParamArrayAttribute attribute, you can pass the objects to the method as individual arguments or as an Object array.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Example: Format more than three arguments

This example creates a string that contains data on the high and low temperature on a particular date. The composite format string has five format items in the C# example and six in the Visual Basic example. Two of the format items define the width of their corresponding value's string representation, and the first format item also includes a standard date and time format string.

using namespace System;

void main()
{
   DateTime date1 = DateTime(2009, 7, 1);
   TimeSpan hiTime = TimeSpan(14, 17, 32);
   Decimal hiTemp = (Decimal) 62.1; 
   TimeSpan loTime = TimeSpan(3, 16, 10);
   Decimal loTemp = (Decimal)54.8; 

   String^ result1 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                                    date1, hiTime, hiTemp, loTime, loTemp);
   Console::WriteLine(result1);
   Console::WriteLine();
           
   String^ result2 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                                    gcnew array<Object^> { date1, hiTime, hiTemp, loTime, loTemp });
   Console::WriteLine(result2);
}
// The example displays the following output:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
DateTime date1 = new DateTime(2009, 7, 1);
TimeSpan hiTime = new TimeSpan(14, 17, 32);
decimal hiTemp = 62.1m; 
TimeSpan loTime = new TimeSpan(3, 16, 10);
decimal loTemp = 54.8m; 

string result1 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                               date1, hiTime, hiTemp, loTime, loTemp);
Console.WriteLine(result1);
Console.WriteLine();
     
string result2 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                               new object[] { date1, hiTime, hiTemp, loTime, loTemp });
Console.WriteLine(result2);
// The example displays output like the following:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
let date1 = DateTime(2009, 7, 1)
let hiTime = TimeSpan(14, 17, 32)
let hiTemp = 62.1m 
let loTime = TimeSpan(3, 16, 10)
let loTemp = 54.8m 

String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", date1, hiTime, hiTemp, loTime, loTemp)
|> printfn "%s\n"
      
String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", [| date1 :> obj; hiTime; hiTemp; loTime; loTemp |])
|> printfn "%s"
// The example displays output like the following:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
Module Example
   Public Sub Main()
      Dim date1 As Date = #7/1/2009#
      Dim hiTime As New TimeSpan(14, 17, 32)
      Dim hiTemp As Decimal = 62.1d 
      Dim loTime As New TimeSpan(3, 16, 10)
      Dim loTemp As Decimal = 54.8d 

      Dim result1 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                           date1, hiTime, hiTemp, loTime, loTemp, vbCrLf)
      Console.WriteLine(result1)
      Console.WriteLine()
           
      Dim result2 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                            New Object() { date1, hiTime, hiTemp, loTime, loTemp, vbCrLf })
      Console.WriteLine(result2)                                            
   End Sub
End Module
' The example displays the following output:
'       Temperature on 7/1/2009:
'          14:17:32: 62.1 degrees (hi)
'          03:16:10: 54.8 degrees (lo)
'
'       Temperature on 7/1/2009:
'          14:17:32: 62.1 degrees (hi)
'          03:16:10: 54.8 degrees (lo)

You can also pass the objects to be formatted as an array rather than as an argument list.

using namespace System;

ref class CityInfo
{
public:
   CityInfo(String^ name, int population, Decimal area, int year)
   {
      this->Name = name;
      this->Population = population;
      this->Area = area;
      this->Year = year;
   }
   
   String^ Name; 
   int Population;
   Decimal Area;
   int Year;
};

ref class Example
{
public:
   static void ShowPopulationData(CityInfo^ city)
   {
      array<Object^>^ args = gcnew array<Object^> { city->Name, city->Year, city->Population, city->Area };
      String^ result = String::Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", 
                                    args);
      Console::WriteLine(result); 
   }
};

void main()
{
   CityInfo^ nyc2010 = gcnew CityInfo("New York", 8175133, (Decimal) 302.64, 2010);
   Example::ShowPopulationData(nyc2010);
   CityInfo^ sea2010 = gcnew CityInfo("Seattle", 608660, (Decimal) 83.94, 2010);      
   Example::ShowPopulationData(sea2010); 
}
// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
using System;

public class CityInfo
{
   public CityInfo(String name, int population, Decimal area, int year)
   {
      this.Name = name;
      this.Population = population;
      this.Area = area;
      this.Year = year;
   }
   
   public readonly String Name; 
   public readonly int Population;
   public readonly Decimal Area;
   public readonly int Year;
}

public class Example
{
   public static void Main()
   {
      CityInfo nyc2010 = new CityInfo("New York", 8175133, 302.64m, 2010);
      ShowPopulationData(nyc2010);
      CityInfo sea2010 = new CityInfo("Seattle", 608660, 83.94m, 2010);      
      ShowPopulationData(sea2010); 
   }

   private static void ShowPopulationData(CityInfo city)
   {
      object[] args = { city.Name, city.Year, city.Population, city.Area };
      String result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", 
                                    args);
      Console.WriteLine(result); 
   }
}
// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
open System

type CityInfo =
  { Name: string
    Population: int
    Area: Decimal
    Year: int }

let showPopulationData city =
    let args: obj[] = [| city.Name; city.Year; city.Population; city.Area |]
    String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
    |> printfn "%s"

{ Name = "New York"; Population = 8175133; Area = 302.64m; Year = 2010 }
|> showPopulationData

 
{ Name = "Seattle"; Population = 608660; Area = 83.94m; Year = 2010 }      
|> showPopulationData 

// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
Public Class CityInfo
   Public Sub New(name As String, population As Integer, area As Decimal, year As Integer)
      Me.Name = name
      Me.Population = population
      Me.Area = area
      Me.Year = year
   End Sub
   
   Public ReadOnly Name As String
   Public ReadOnly Population As Integer
   Public ReadOnly Area As Decimal
   Public ReadOnly Year As Integer
End Class

Module Example
   Public Sub Main()
      Dim nyc2010 As New CityInfo("New York", 8175133, 302.64d, 2010)
      ShowPopulationData(nyc2010)
      Dim sea2010 As New CityInfo("Seattle", 608660, 83.94d, 2010)      
      ShowPopulationData(sea2010) 
   End Sub
   
   Private Sub ShowPopulationData(city As CityInfo)
      Dim args() As Object = { city.Name, city.Year, city.Population, city.Area }
      Dim result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
      Console.WriteLine(result) 
   End Sub
End Module
' The example displays the following output:
'       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
'       Seattle in 2010: Population 608,660, Area 83.9 sq. feet

See also

Applies to

Format(String, Object)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces one or more format items in a string with the string representation of a specified object.

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0);
public static string Format (string format, object arg0);
public static string Format (string format, object? arg0);
static member Format : string * obj -> string
Public Shared Function Format (format As String, arg0 As Object) As String

Parameters

arg0
Object

The object to format.

Returns

A copy of format in which any format items are replaced by the string representation of arg0.

Exceptions

format is null.

The format item in format is invalid.

-or-

The index of a format item is not zero.

Remarks

Important

Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).

This method uses the composite formatting feature to convert the value of an expression to its string representation and to embed that representation in a string.

However, when calling the String.Format method, it's not necessary to focus on the particular overload that you want to call. Instead, you can call the method with a composite format string that includes one or more format items. You assign each format item a numeric index; the first index starts at 0. In addition to the initial string, your method call should have as many additional arguments as it has index values. For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. The language compiler will then resolve your method call to a particular overload of the String.Format method.

For more detailed documentation on using the String.Format method, see Get started with the String.Format method and Which method do I call?.

Example: Formatting a single argument

The following example uses the Format(String, Object) method to embed an individual's age in the middle of a string.

using namespace System;

void main()
{
   DateTime birthdate = DateTime(1993, 7, 28);
   array<DateTime>^ dates = gcnew array<DateTime> { DateTime(1993, 8, 16), 
                                                    DateTime(1994, 7, 28), 
                                                    DateTime(2000, 10, 16), 
                                                    DateTime(2003, 7, 27), 
                                                    DateTime(2007, 5, 27) };

   for each (DateTime dateValue in dates)
   {
      TimeSpan interval = dateValue - birthdate;
      // Get the approximate number of years, without accounting for leap years.
      int years = ((int)interval.TotalDays) / 365;
      // See if adding the number of years exceeds dateValue.
      String^ output;
      if (birthdate.AddYears(years) <= dateValue) {
         output = String::Format("You are now {0} years old.", years);
         Console::WriteLine(output);
      }   
      else {
         output = String::Format("You are now {0} years old.", years - 1);
         Console::WriteLine(output);
      }      
   }
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
DateTime birthdate = new DateTime(1993, 7, 28);
DateTime[] dates = { new DateTime(1993, 8, 16), 
                     new DateTime(1994, 7, 28), 
                     new DateTime(2000, 10, 16), 
                     new DateTime(2003, 7, 27), 
                     new DateTime(2007, 5, 27) };

foreach (DateTime dateValue in dates)
{
   TimeSpan interval = dateValue - birthdate;
   // Get the approximate number of years, without accounting for leap years.
   int years = ((int) interval.TotalDays) / 365;
   // See if adding the number of years exceeds dateValue.
   string output;
   if (birthdate.AddYears(years) <= dateValue) {
      output = String.Format("You are now {0} years old.", years);
      Console.WriteLine(output);
   }   
   else {
      output = String.Format("You are now {0} years old.", years - 1);
      Console.WriteLine(output);
   }      
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
let birthdate = DateTime(1993, 7, 28)
let dates = 
    [ DateTime(1993, 8, 16) 
      DateTime(1994, 7, 28)
      DateTime(2000, 10, 16)
      DateTime(2003, 7, 27)
      DateTime(2007, 5, 27) ]

for dateValue in dates do
    let interval = dateValue - birthdate
    // Get the approximate number of years, without accounting for leap years.
    let years = (int interval.TotalDays) / 365
    // See if adding the number of years exceeds dateValue.
    if birthdate.AddYears years <= dateValue then
        String.Format("You are now {0} years old.", years)
    else
        String.Format("You are now {0} years old.", years - 1)
    |> printfn "%s"
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
Module Example
   Public Sub Main()
      Dim birthdate As Date = #7/28/1993#
      Dim dates() As Date = { #9/16/1993#, #7/28/1994#, #10/16/2000#, _
                              #7/27/2003#, #5/27/2007# }
      For Each dateValue As Date In dates
         Dim interval As TimeSpan = dateValue - birthdate
         ' Get the approximate number of years, without accounting for leap years.
         Dim years As Integer = CInt(interval.TotalDays) \ 365
         ' See if adding the number of years exceeds dateValue.
         Dim output As String
         If birthdate.AddYears(years) <= dateValue Then
            output = String.Format("You are now {0} years old.", years)
            Console.WriteLine(output)
         Else
            output = String.Format("You are now {0} years old.", years - 1)
            Console.WriteLine(output)   
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       You are now 0 years old.
'       You are now 1 years old.
'       You are now 7 years old.
'       You are now 9 years old.
'       You are now 13 years old.

See also

Applies to

Format(IFormatProvider, CompositeFormat, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider? provider, System.Text.CompositeFormat format, params object?[] args);
static member Format : IFormatProvider * System.Text.CompositeFormat * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As CompositeFormat, ParamArray args As Object()) As String

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

args
Object[]

An array of objects to format.

Returns

The formatted string.

Exceptions

format or args is null.

The index of a format item is greater than or equal to the number of supplied arguments.

Applies to

Format<TArg0,TArg1,TArg2>(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

public:
generic <typename TArg0, typename TArg1, typename TArg2>
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, TArg0 arg0, TArg1 arg1, TArg2 arg2);
public static string Format<TArg0,TArg1,TArg2> (IFormatProvider? provider, System.Text.CompositeFormat format, TArg0 arg0, TArg1 arg1, TArg2 arg2);
static member Format : IFormatProvider * System.Text.CompositeFormat * 'TArg0 * 'TArg1 * 'TArg2 -> string
Public Shared Function Format(Of TArg0, TArg1, TArg2) (provider As IFormatProvider, format As CompositeFormat, arg0 As TArg0, arg1 As TArg1, arg2 As TArg2) As String

Type Parameters

TArg0

The type of the first object to format.

TArg1

The type of the second object to format.

TArg2

The type of the third object to format.

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

arg0
TArg0

The first object to format.

arg1
TArg1

The second object to format.

arg2
TArg2

The third object to format.

Returns

The formatted string.

Exceptions

format is null.

The index of a format item is greater than or equal to the number of supplied arguments.

Applies to

Format<TArg0,TArg1>(IFormatProvider, CompositeFormat, TArg0, TArg1)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

public:
generic <typename TArg0, typename TArg1>
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, TArg0 arg0, TArg1 arg1);
public static string Format<TArg0,TArg1> (IFormatProvider? provider, System.Text.CompositeFormat format, TArg0 arg0, TArg1 arg1);
static member Format : IFormatProvider * System.Text.CompositeFormat * 'TArg0 * 'TArg1 -> string
Public Shared Function Format(Of TArg0, TArg1) (provider As IFormatProvider, format As CompositeFormat, arg0 As TArg0, arg1 As TArg1) As String

Type Parameters

TArg0

The type of the first object to format.

TArg1

The type of the second object to format.

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

arg0
TArg0

The first object to format.

arg1
TArg1

The second object to format.

Returns

The formatted string.

Exceptions

format is null.

The index of a format item is greater than or equal to the number of supplied arguments.

Applies to

Format<TArg0>(IFormatProvider, CompositeFormat, TArg0)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Replaces the format item or items in a CompositeFormat with the string representation of the corresponding objects in the specified format.

public:
generic <typename TArg0>
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, TArg0 arg0);
public static string Format<TArg0> (IFormatProvider? provider, System.Text.CompositeFormat format, TArg0 arg0);
static member Format : IFormatProvider * System.Text.CompositeFormat * 'TArg0 -> string
Public Shared Function Format(Of TArg0) (provider As IFormatProvider, format As CompositeFormat, arg0 As TArg0) As String

Type Parameters

TArg0

The type of the first object to format.

Parameters

provider
IFormatProvider

An object that supplies culture-specific formatting information.

arg0
TArg0

The first object to format.

Returns

The formatted string.

Exceptions

format is null.

The index of a format item is greater than or equal to the number of supplied arguments.

Applies to