다음을 통해 공유


String.Format Method (String, Object)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function Format ( _
    format As String, _
    arg0 As Object _
) As String
public static string Format(
    string format,
    Object arg0
)

Parameters

  • format
    Type: System.String
    A composite format string (see Remarks).

Return Value

Type: System.String
A copy of format in which the first format item has been replaced by the string representation of arg0.

Exceptions

Exception Condition
ArgumentNullException

format is nulla null reference (Nothing in Visual Basic).

FormatException

The format item in format is invalid.

-or-

The index of a format item is not zero.

Remarks

This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its string representation and embed that representation in a string. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics.

The format parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to an object in the parameter list of this method. The formatting process replaces each format item with the string representation of the corresponding object.

The syntax of a format item is as follows:

{index[,length][:formatString]}

Elements in square brackets are optional. The following table describes each element. For more information about the composite formatting feature, including the syntax of a format item, see Composite Formatting.

Element

Description

index

The zero-based position in the parameter list of the object to be formatted. If the object specified by index is nulla null reference (Nothing in Visual Basic), the format item is replaced by String.Empty. Because this overload has only a single object in its parameter list, the value of index must always be 0. If there is no parameter in the index position, a FormatException is thrown.

,length

The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned.

:formatString

A standard or custom format string that is supported by the parameter. Possible values for formatString are the same as the values supported by the object's ToString(format) method. If formatString is not specified and the object to be formatted implements the IFormattable interface, nulla null reference (Nothing in Visual Basic) is passed as the value of the format parameter that is used as the IFormattable.ToString format string.

NoteNote:

For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the standard format strings used with enumerations, see Enumeration Format Strings.

The leading and trailing brace characters, '{' and '}', are required. To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".

Although the String.Format(String, Object) method has a single object in its parameter list, format can include more than one format item as long as each has the same index. In the following example, the format string includes two format items with the same index: one displays the decimal value of a number and the other displays its hexadecimal value.

Imports System.Windows.Media

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      outputBlock.FontFamily = New FontFamily("Courier New")

      Dim values() As Short = {Int16.MinValue, -27, 0, 1042, Int16.MaxValue}
      outputBlock.Text &= String.Format("{0,10}  {1,10}", "Decimal", "Hex") & vbCrLf
      outputBlock.Text &= vbCrLf
      For Each value As Short In values
         Dim formatString As String = String.Format("{0,10:G}: {0,10:X}", value)
         outputBlock.Text &= formatString & vbCrLf
      Next
   End Sub
End Module
' The example displays the following output:
'       Decimal         Hex
'    
'        -32768:       8000
'           -27:       FFE5
'             0:          0
'          1042:        412
'         32767:       7FFF
public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.FontFamily = new FontFamily("Courier New");

      short[] values = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
      outputBlock.Text += String.Format("{0,10}  {1,10}\n\n", "Decimal", "Hex");
      foreach (short value in values)
      {
         string formatString = String.Format("{0,10:G}: {0,10:X}", value);
         outputBlock.Text += formatString + "\n";
      }
   }
}
// The example displays the following output:
//       Decimal         Hex
//    
//        -32768:       8000
//           -27:       FFE5
//             0:          0
//          1042:        412
//         32767:       7FFF

If the value of format is, "Thank you for your purchase of {0:####} copies of Microsoft®.NET (Core Reference).", and arg0 is an Int16 with the value 123, then the return value will be:

"Thank you for your purchase of 123 copies of Microsoft®.NET (Core Reference)."

If the value of format is, "Brad's dog has {0,-8:G} fleas.", arg0 is an Int16 with the value 42, (and in this example, underscores represent padding spaces) then the return value will be:

"Brad's dog has 42______ fleas."

Examples

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

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      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.
         If birthdate.AddYears(years) <= dateValue Then
            outputBlock.Text += String.Format("You are now {0} years old.", years) & vbCrLf
         Else
            outputBlock.Text += String.Format("You are now {0} years old.", years - 1) & vbCrLf
         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.
using System;

[assembly: CLSCompliant(true)]
public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      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.
         if (birthdate.AddYears(years) <= dateValue)
            outputBlock.Text += String.Format("You are now {0} years old.", years) + "\n";
         else
            outputBlock.Text += String.Format("You are now {0} years old.", years - 1) + "\n";
      }
   }
}
// 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.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.