Exportera (0) Skriv ut
Visa allt
EN
Det här innehållet finns inte tillgängligt på ditt språk men här finns den engelska versionen,
10 av 30 bedömde detta vara till hjälp - Bedöm det här ämnet

String.Format Method

Replaces each format item in a specified string with the text equivalent of a corresponding object's value.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method Static member Format(String, Object) Replaces one or more format items in a specified string with the string representation of a specified object.
Public method Static member Format(String, Object[]) Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
Public method Static member Format(IFormatProvider, String, Object[]) Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.
Public method Static member Format(String, Object, Object) Replaces the format items in a specified string with the string representation of two specified objects.
Public method Static member Format(String, Object, Object, Object) Replaces the format items in a specified string with the string representation of three specified objects.
Top

In this section:

Overloaded method syntax
Parameters
Return value
Exceptions
Which method do I call?
The Format method in brief
The Format item
How arguments are formatted
Format items that have the same index
Formatting and culture
Custom formatting operations
Examples:
       Formatting a single argument
       Formatting two arguments
       Formatting three arguments
       Formatting more than three arguments
       Culture-sensitive formatting
       A custom formatting operation
       An intercept provider and Roman numeral formatter
Version information

Overloaded method syntax

For additional guidance on choosing an overload, see Which method do I call?

String String.Format(String format , Object arg0 )

Replaces the format items with the string representation of a specified object (example).

String String.Format(String format , Object arg0 , Object arg1 )

Replaces the format items with the string representation of two specified objects (example).

String String.Format(String format , Object arg0 , Object arg1 , Object arg2 )

Replaces the format items with the string representation of three specified objects (example).

String String.Format(String format , params Object[] args )

Replaces the format items with the string representations of corresponding objects in a specified array (example).

String String.Format(IFormatProvider provider , String format , params Object[] args )

Replaces the format items with the string representation of corresponding objects in a specified array, and uses the specified culture-specific formatting information (example) or custom formatting information (example).

Parameters

This is a complete list of parameters for the Format method; see the overload syntax above for the parameters used by each overload. Only the format parameter is used by all overloads.

Parameter

Type

Description

s

String

A composite format string that includes one or more format items (see The format item).

arg0

String

The first or only object to format.

arg1

String

The second object to format.

arg2

String

The third object to format.

args

String []

Zero or more objects to format, supplied either in a comma-delimited list or as an array.

provider

IFormatProvider

An object that supplies custom or culture-specific formatting information.

Return value

Type: String
A copy of format in which the format items have been replaced by the string representations of the corresponding arguments.

Exceptions

Exception

Condition

Thrown by

ArgumentNullException

format is null.

All overloads.

FormatException

format is invalid.

-or-

The index of a format item is less than zero, or greater than or equal to the number of arguments in the arguments list.

All overloads.

Which method do I call?

To

Call

Format one or more objects by using the conventions of the current culture.

Except for the overload that includes a provider parameter, all Format overloads include a String parameter followed by one or more object parameters. Because of this, you do not have to determine which Format overload you intend to call. Your language compiler will select the appropriate overload from among the overloads that don't have a provider parameter, based on your argument list. For example, if your argument list has five arguments, the compiler will call the Format(String, Object[]) method.

Format one or more objects by using the conventions of a specific culture.

Format(IFormatProvider, String, Object[])

Perform a custom formatting operation either with an ICustomFormatter implementation or an IFormattable implementation.

Format(IFormatProvider, String, Object[])

The Format method in brief

Each overload of the Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is null, the format item is replaced with String.Empty. For example, the following call to the Format(String, Object, Object, Object) method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items.

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                              dat, city, temp);
Console.WriteLine(output);
// The example displays the following output: 
//    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   

The format item

A format item has this syntax:

{ index[,alignment][ :formatString] }

Brackets denote optional elements. The opening and closing braces are required. (To include a literal opening or closing brace in the format string, see the "Escaping Braces" section in the Composite Formatting article.)

For example, a format item to format a currency value might appears like this:

String.Format("{0,-10:C}", 126347.89m);         

A format item has the following elements:

index

The zero-based index of the argument whose string representation is to be included at this position in the string. If this argument is null, an empty string will be included at this position in the string.

alignment

Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.

formatString

Optional. A string that specifies the format of the corresponding argument's result string. If you omit formatString, the corresponding argument's parameterless ToString method is called to produce its string representation. If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. Types that support format strings include:

However, note that any custom type can implement IFormattable or extend an existing type's IFormattable implementation.

The following example uses the alignment and formatString arguments to produce formatted output.

using System;

public class Example
{
   public static void Main()
   {
      // Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
      Tuple<string, DateTime, int, DateTime, int>[] cities = 
          { Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277, 
                         new DateTime(1950, 1, 1), 1970358),
            Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995, 
                         new DateTime(1950, 1, 1), 7891957),  
            Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808, 
                         new DateTime(1950, 1, 1), 3620962),  
            Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452, 
                         new DateTime(1950, 1, 1), 1849568) };

      // Display header 
      string header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                                    "City", "Year", "Population", "Change (%)");
      Console.WriteLine(header);
      string output;      
      foreach (var city in cities) {
         output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/ (double)city.Item3);
         Console.WriteLine(output);
      }
   }
}
// The example displays the following output: 
//    City            Year  Population    Year  Population    Change (%) 
//     
//    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 % 
//    New York        1940   7,454,995    1950   7,891,957         5.9 % 
//    Chicago         1940   3,396,808    1950   3,620,962         6.6 % 
//    Detroit         1940   1,623,452    1950   1,849,568        13.9 %

How arguments are formatted

Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The Format method retrieves the argument and derives its string representation as follows:

For an example that intercepts calls to the ICustomFormatter.Format method and allows you to see what information the Format method passes to a formatting method for each format item in a composite format string, see Example 7: An intercept provider and Roman numeral formatter.

Format items that have the same index

The Format method throws a FormatException exception if the index of an index item is greater than or equal to the number of arguments in the argument list. However, format can include more format items than there are arguments, as long as multiple format items have the same index. In the call to the Format(String, Object) method in following example, the argument list has a single argument, but the format string includes two format items: one displays the decimal value of a number, and the other displays its hexadecimal value.

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

Formatting and culture

Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the CultureInfo.CurrentCulture property. You can control this behavior by calling the Format(IFormatProvider, String, Object[]) overload. This overload's provider parameter is an IFormatProvider implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process.

The IFormatProvider interface has a single member, GetFormat, which is responsible for returning the object that provides formatting information. The .NET Framework has three IFormatProvider implementations that provide culture-specific formatting:

Custom formatting operations

You can also call the Format(IFormatProvider, String, Object[]) overload to perform custom formatting operations. For example, you could format an integer as an identification number or as a telephone number. To perform custom formatting, your provider argument must implement both the IFormatProvider and ICustomFormatter interfaces. When the Format(IFormatProvider, String, Object[]) method is passed an ICustomFormatter implementation as the provider argument, the Format method calls its IFormatProvider.GetFormat implementation and requests an object of type ICustomFormatter. It then calls the returned ICustomFormatter object's Format method to format each format item in the composite string passed to it.

For more information about providing custom formatting solutions, see How to: Define and Use Custom Numeric Format Providers and ICustomFormatter. For an example that converts integers to formatted custom numbers, see Example 6: A custom formatting operation. For an example that converts unsigned bytes to Roman numerals, see Example 7: An intercept provider and Roman numeral formatter.

Example 1: 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 System;

[assembly: CLSCompliant(true)]
public class Example
{
   public static void Main()
   {
      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.

Example 2: Formatting 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 System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      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 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

Example 3: Formatting 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 System;

public class Example
{
   public static 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)

Example 4: Formatting 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 System;

public class Example
{
   public static void Main()
   {
      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 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 a an argument list.

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

Example 5: 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.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      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)
      {
         CultureInfo culture = new 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

Example 6: A custom formatting operation

This example defines a format provider that formats an integer value as a customer account number in the form x-xxxxx-xx.

using System;

public class TestFormatter
{
   public static void Main()
   {
      int acctNumber = 79203159;
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
      try {
         Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
      }
      catch (FormatException e) {
         Console.WriteLine(e.Message);
      }
   }
}

public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(ICustomFormatter))        
         return this; 
      else 
         return null;
   }

   public string Format(string format, 
	                     object arg, 
	                     IFormatProvider formatProvider) 
   {                       
      if (! this.Equals(formatProvider))
      {
         return null;
      }
      else
      {
         if (String.IsNullOrEmpty(format)) 
            format = "G";

         string customerString = arg.ToString();
         if (customerString.Length < 8)
            customerString = customerString.PadLeft(8, '0');

         format = format.ToUpper();
         switch (format)
         {
            case "G":
               return customerString.Substring(0, 1) + "-" +
                                     customerString.Substring(1, 5) + "-" +
                                     customerString.Substring(6);
            case "S":                          
               return customerString.Substring(0, 1) + "/" +
                                     customerString.Substring(1, 5) + "/" +
                                     customerString.Substring(6);
            case "P":                          
               return customerString.Substring(0, 1) + "." +
                                     customerString.Substring(1, 5) + "." +
                                     customerString.Substring(6);
            default:
               throw new FormatException( 
                         String.Format("The '{0}' format specifier is not supported.", format));
         }
      }   
   }
}
// The example displays the following output: 
//       7-92031-59 
//       7-92031-59 
//       7/92031/59 
//       7.92031.59 
//       The 'X' format specifier is not supported.

Example 7: An intercept provider and Roman numeral formatter

This example defines a custom format provider that implements the ICustomFormatter and IFormatProvider interfaces to do two things:

  • It displays the parameters passed to its ICustomFormatter.Format implementation. This enables us to see what parameters the Format(IFormatProvider, String, Object[]) method is passing to the custom formatting implementation for each object that it tries to format. This can be useful when you're debugging your application.

  • If the object to be formatted is an unsigned byte value that is to be formatted by using the "R" standard format string, the custom formatter formats the numeric value as a Roman numeral.

using System;
using System.Globalization;

public class InterceptProvider : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else 
         return null;
   }

   public string Format(String format, Object obj, IFormatProvider provider) 
   {
      // Display information about method call. 
      string formatString = format ?? "<null>";
      Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
                        provider, obj ?? "<null>", formatString);

      if (obj == null) return String.Empty;

      // If this is a byte and the "R" format string, format it with Roman numerals.
      if (obj is Byte && formatString.ToUpper().Equals("R")) {
         Byte value = (Byte) obj;
         int remainder;
         int result;
         String returnString = String.Empty;

         // Get the hundreds digit(s)
         result = Math.DivRem(value, 100, out remainder);
         if (result > 0)  
            returnString = new String('C', result);
         value = (Byte) remainder;
         // Get the 50s digit
         result = Math.DivRem(value, 50, out remainder);
         if (result == 1)
            returnString += "L";
         value = (Byte) remainder;
         // Get the tens digit.
         result = Math.DivRem(value, 10, out remainder);
         if (result > 0)
            returnString += new String('X', result);
         value = (Byte) remainder; 
         // Get the fives digit.
         result = Math.DivRem(value, 5, out remainder);
         if (result > 0)
            returnString += "V";
         value = (Byte) remainder;
         // Add the ones digit. 
         if (remainder > 0) 
            returnString += new String('I', remainder);

         // Check whether we have too many X characters. 
         int pos = returnString.IndexOf("XXXX");
         if (pos >= 0) {
            int xPos = returnString.IndexOf("L"); 
            if (xPos >= 0 & xPos == pos - 1)
               returnString = returnString.Replace("LXXXX", "XC");
            else
               returnString = returnString.Replace("XXXX", "XL");   
         }
         // Check whether we have too many I characters
         pos = returnString.IndexOf("IIII");
         if (pos >= 0)
            if (returnString.IndexOf("V") >= 0)
               returnString = returnString.Replace("VIIII", "IX");
            else
               returnString = returnString.Replace("IIII", "IV");    

         return returnString; 
      }   

      // Use default for all other formatting. 
      if (obj is IFormattable)
         return ((IFormattable) obj).ToString(format, CultureInfo.CurrentCulture);
      else 
         return obj.ToString();
   }
}

public class Example
{
   public static void Main()
   {
      int n = 10;
      double value = 16.935;
      DateTime day = DateTime.Now;
      InterceptProvider provider = new InterceptProvider();
      Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
      Console.WriteLine(String.Format(provider, "{0}: {1:F}\n", "Today: ", 
                                      (DayOfWeek) DateTime.Now.DayOfWeek));
      Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n", 
                                      (Byte) 2, (Byte) 12, (Byte) 199));
      Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}\n", 
                                      (Byte) 2, (Byte) 12, (Byte) 199));
   }
}
// The example displays the following output: 
//    Provider: InterceptProvider, Object: 10, Format String: N0 
//    Provider: InterceptProvider, Object: 16.935, Format String: C2 
//    Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d 
//    10: $16.94 on 1/31/2013 
//     
//    Provider: InterceptProvider, Object: Today: , Format String: <null> 
//    Provider: InterceptProvider, Object: Thursday, Format String: F 
//    Today: : Thursday 
//     
//    Provider: InterceptProvider, Object: 2, Format String: X 
//    Provider: InterceptProvider, Object: 12, Format String: <null> 
//    Provider: InterceptProvider, Object: 199, Format String: <null> 
//    2, 12, 199 
//     
//    Provider: InterceptProvider, Object: 2, Format String: R 
//    Provider: InterceptProvider, Object: 12, Format String: R 
//    Provider: InterceptProvider, Object: 199, Format String: R 
//    II, XII, CXCIX

Version information

.NET Framework

All overloads are supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

All overloads are supported in: 4, 3.5 SP1

Portable Class Library

Only Format(String, Object[]) and Format(IFormatProvider, String, Object[]) are supported

.NET for Windows Store apps

Only Format(String, Object[]) and Format(IFormatProvider, String, Object[]) are supported in Windows 8

Var detta till hjälp?
(1500 tecken kvar)
Tack för dina kommentarer
Visa:
© 2014 Microsoft. Med ensamrätt.