本文為機器翻譯文章。如需檢視英文版，請選取 [原文] 核取方塊。您也可以將滑鼠指標移到文字上，即可在快顯視窗顯示英文原文。 譯文 原文

# String.Format 方法

.NET Framework (current version)

## 多載清單

Format(IFormatProvider, String, Object)

Format(IFormatProvider, String, Object, Object)

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

Format(IFormatProvider, String, Object[])

Format(String, Object)

Format(String, Object, Object)

Format(String, Object, Object, Object)

Format(String, Object[])

## 註解

### String.Format 方法入門

```Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0} per ounce.",
pricePerOunce);
// Result: The current price is 17.36 per ounce.
```

```Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.",
pricePerOunce);
// Result if current culture is en-US:
//      The current price is \$17.36 per ounce.
```

String.Format開始使用的格式字串，後面接著一個或多個物件會轉換成字串並插入格式字串中的指定位置的運算式。 例如:

```decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
```

{0}格式字串是格式項目。 0這是的物件的字串值將會插入該位置的索引。 （索引 0 開始。） 如果要插入的物件不是字串，其ToString呼叫方法，將它轉換成插入結果字串中之前的其中一個。

```string s = String.Format("At {0}, the temperature is {1}°C.",
DateTime.Now, 20.4);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
```

```string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
```

```int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
String s = String.Format("{0,6} {1,15}\n\n", "Year", "Population");
for(int index = 0; index < years.Length; index++)
s += String.Format("{0,6} {1,15:N0}\n",
years[index], population[index]);
// Result:
//      Year      Population
//
//      2013       1,025,632
//      2014       1,105,967
//      2015       1,148,203
```

```int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
String s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years.Length; index++)
s += String.Format("{0,-10} {1,-10:N0}\n",
years[index], population[index]);
// Result:
//    Year       Population
//
//    2013       1,025,632
//    2014       1,105,967
//    2015       1,148,203
```

String.Format使用複合格式功能。 如需詳細資訊，請參閱複合格式

### 多載的方法的語法

String String.Format(String format, Object arg0)

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

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

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

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

format

String

arg0

String

arg1

String

arg2

String

args

String[]

provider

IFormatProvider

### 例外狀況

ArgumentNullException

formatnull

FormatException

format 無效。

-或-

### Format 方法簡介

```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.
```

### 格式項目

```
{
index[,alignment][ :formatString] }
```

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

formatString

```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) };

"City", "Year", "Population", "Change (%)");
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 %
```

### 格式項目具有相同的索引

Format方法會擲回FormatException索引項目的索引是否大於或等於引數清單中的引數的例外狀況。 不過，format可以包含多個格式項目比引數，只要多個格式項目具有相同的索引。 在呼叫Format(String, Object)在下列範例中，引數清單的方法具有單一引數，但是格式字串包含兩個格式項目︰ 一個顯示數字的十進位值與另一個則顯示十六進位值。

```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
```

### 格式和文化特性

IFormatProvider介面具有單一成員， GetFormat，這是負責傳回的物件，提供格式設定資訊。 .NET Framework 有三個IFormatProvider實作，以提供特定文化特性的格式︰

### 範例 1︰ 格式為單一引數

```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;
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.
```

### 範例 2︰ 設定格式化的兩個引數

```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
```

### 範例 3︰ 設定格式化的三個引數

```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)
```

### 範例 4︰ 設定格式化的三個以上的引數

```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)
```

```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 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
```

### 範例 5︰ 區分文化特性的格式化

```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
```

### 範例 6︰ 自訂格式化作業

```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)

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.
```

### 範例 7: 截距，提供者和羅馬數字格式器

• 它會顯示參數傳遞至其ICustomFormatter.Format實作。 這可讓我們查看哪些參數Format(IFormatProvider, String, Object[])方法將傳遞至自訂的格式實作每個物件，它會嘗試格式化。 當您在偵錯您的應用程式，這非常有用。

• 要格式化的物件是否要使用"R"標準格式字串格式化為不帶正負號的位元組值，將自訂格式器會格式化為羅馬數字的數字的值。

```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;
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
```

### 版本資訊

.NET Framework

.NET Framework Client Profile

### String.Format Q & A

#### 如何控制結果字串時，取代的項目格式的對齊方式？

```{index[,alignment][: formatString]}
```

#### 如何控制十進位分隔符號之後的數字位數？

```using System;

public class Example
{
public static void Main()
{
object[] values = { 1603, 1794.68235, 15436.14 };
string result;
foreach (var value in values) {
result = String.Format("{0,12:C2}   {0,12:E3}   {0,12:F4}   {0,12:N3}  {1,12:P2}\n",
Convert.ToDouble(value), Convert.ToDouble(value) / 10000);
Console.WriteLine(result);
}
}
}
// The example displays the following output:
//       \$1,603.00     1.603E+003      1603.0000      1,603.000       16.03 %
//
//       \$1,794.68     1.795E+003      1794.6824      1,794.682       17.95 %
//
//      \$15,436.14     1.544E+004     15436.1400     15,436.140      154.36 %
```

```using System;

public class Example
{
public static void Main()
{
decimal value = 16309.5436m;
string result = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}",
value);
Console.WriteLine(result);
}
}
// The example displays the following output:
//        16309.54360    16,309.54    16309.544
```

#### 如何控制整數位數數的字？

```using System;

public class Example
{
public static void Main()
{
int value = 1326;
string result = String.Format("{0,10:D6} {0,10:X8}", value);
Console.WriteLine(result);
}
}
// The example displays the following output:
//     001326   0000052E
```

```using System;

public class Example
{
public static void Main()
{
int value = 16342;
string result = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}",
value);
Console.WriteLine(result);
}
}
// The example displays the following output:
//           00016342       00016342.000    0,000,016,342.0
```

#### 如何包含常值的大括號 ("{"和"}") 在結果字串中？

```result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
nOpen, nClose);
```

```result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose);
```

```result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}");
```

#### 如果 Format(System.IFormatProvider,System.String,System.Object[]) 方法支援參數陣列，為什麼我的程式碼回例外狀況時使用陣列嗎？

```using System;
using System.Collections.Generic;

public class Example
{
public static void Main()
{
Random rnd = new Random();
int[]  numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
int number = rnd.Next(1001);
numbers[ctr] = number;
total += number;
}
numbers[3] = total;
Console.WriteLine("{0} + {1} + {2} = {3}", numbers);
}
}
```

Visual Basic 或 C# 都不可以轉換成物件陣列的整數陣列，所以您必須自行執行轉換，然後再呼叫Format(String, Object[])方法。 下列範例提供一個實作。

```using System;
using System.Collections.Generic;

public class Example
{
public static void Main()
{
Random rnd = new Random();
int[]  numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
int number = rnd.Next(1001);
numbers[ctr] = number;
total += number;
}
numbers[3] = total;
object[] values = new object[numbers.Length];
numbers.CopyTo(values, 0);
Console.WriteLine("{0} + {1} + {2} = {3}", values);
}
}
```