String.Format メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定された形式に基づいてオブジェクトの値を文字列に変換し、別の文字列に挿入します。
String.Format メソッドを初めて使用する場合は、「Get started with the String.Format method」(String.Format メソッドの概要) セクションを参照して、概要をご確認ください。
String.Format メソッドの全般的な説明については、「Remarks」 (解説) セクションを参照してください。
オーバーロード
| Format(String, Object) |
文字列の 1 つ以上の書式項目を、指定されたオブジェクトの文字列表記に置換します。 |
| Format(String, Object[]) |
指定した文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列形式に置換します。 |
| Format(IFormatProvider, String, Object) |
指定した文字列の 1 つまたは複数の書式項目を、対応するオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。 |
| Format(IFormatProvider, String, Object[]) |
文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列表記に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。 |
| Format(String, Object, Object) |
文字列の書式項目を、指定した 2 つのオブジェクトの文字列形式に置換します。 |
| Format(IFormatProvider, String, Object, Object) |
文字列の書式項目を、指定した 2 つのオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。 |
| Format(String, Object, Object, Object) |
文字列の書式項目を、指定した 3 つのオブジェクトの文字列形式に置換します。 |
| Format(IFormatProvider, String, Object, Object, Object) |
文字列の書式項目を、指定した 3 つのオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式設定情報を指定します。 |
例
この記事の「解説」では、メソッドを呼び出す多くの例を示し Format ています。
String.Format C# 用の .net Core プロジェクトが含まれている例の完全なセットをダウンロードすることもできます。
記事に含まれている例の一部を次に示します。
書式指定文字列の作成
文字列の挿入
書式項目
同じインデックスを持つ項目を書式設定する
書式設定された出力の制御
書式設定の制御
制御 (間隔を)
制御 (配置を)
整数部の桁数を制御する
小数点区切り文字の後の桁数を制御する
結果の文字列にリテラルの中かっこを含める
書式指定文字列のカルチャを区別する
書式設定操作をカスタマイズする
カスタムの書式設定操作
インターセプトプロバイダーとローマ数字フォーマッタ
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このセクションの内容:
概要 String.Format メソッドを使用する
どのメソッドを呼び出しますか?
Format メソッドの概要
[書式] 項目
引数の書式設定方法
同じインデックスを持つ項目の書式を設定する
書式設定とカルチャ
カスタム書式設定操作
String.Format Q & A
概要 String.Format メソッドを使用する
オブジェクト String.Format 、変数、または式の値を別の文字列に挿入する必要がある場合は、 を使用します。 たとえば、値の値を文字列に挿入して、1 つの文字列としてユーザー Decimal に表示できます。
Decimal pricePerOunce = (Decimal)17.36;
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} per ounce.",
pricePerOunce);
Console.WriteLine(s);
// Result: The current price is 17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0} per ounce.",
pricePerOunce)
' Result: The current price is 17.36 per ounce.
また、その値の書式設定を制御できます。
Decimal pricePerOunce = (Decimal)17.36;
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.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.",
pricePerOunce);
Console.WriteLine(s);
// Result if current culture is en-US:
// The current price is $17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = 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 は書式指定文字列で始まり、その後に 1 つ以上のオブジェクトまたは式が続き、文字列に変換され、書式指定文字列内の指定した場所に挿入されます。 次に例を示します。
Decimal temp = (Decimal)20.4;
String^ s = String::Format("The temperature is {0}°C.", temp);
Console::WriteLine(s);
// Displays 'The temperature is 20.4°C.'
decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
Dim temp As Decimal = 20.4d
Dim s As String = String.Format("The temperature is {0}°C.", temp)
Console.WriteLine(s)
' Displays 'The temperature is 20.4°C.'
書式 {0} 指定文字列の は書式項目です。 0 は、文字列値をその位置に挿入するオブジェクトのインデックスです。 (インデックスは 0 から始まる)。挿入するオブジェクトが文字列ではない場合、そのメソッドが呼び出され、結果文字列に挿入する前に、そのオブジェクトが 1 に ToString 変換されます。
オブジェクト リストで 2 つの書式項目と 2 つのオブジェクトを使用する別の例を次に示します。
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("At {0}, the temperature is {1}°C.",
DateTime.Now, 20.4);
Console.WriteLine(s);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
Dim s As String = String.Format("At {0}, the temperature is {1}°C.",
Date.Now, 20.4)
' Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
すべての書式項目のインデックスにオブジェクト リスト内に一致するオブジェクトがある限り、オブジェクト リスト内の書式項目とオブジェクトの数を必要な数にできます。 また、どのオーバーロードを呼び出すのか心配する必要はありません。コンパイラによって適切なオプションが選択されます。
書式設定を制御する
書式指定項目のインデックスの後に書式指定文字列を付け、オブジェクトの書式設定方法を制御できます。 たとえば、 は {0:d} 、オブジェクト リストの最初のオブジェクトに "d" 書式指定文字列を適用します。 1 つのオブジェクトと 2 つの書式項目の例を次に示します。
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'
string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
Console.WriteLine(s);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
Dim s As String = String.Format("It is now {0:d} at {0:t}",
Date.Now)
' Output similar to: 'It is now 4/10/2015 at 10:04 AM'
多くの型では、すべての数値型 (標準書式指定文字列とカスタム書式指定文字列の両方)、すべての日付と時刻(標準書式指定文字列とカスタム書式指定文字列の両方)、時間間隔 (標準書式指定文字列とカスタム書式指定文字列の両方)、すべての列挙型列挙型、GUIDなど、書式指定文字列がサポートされています。 書式指定文字列のサポートを独自の型に追加することもできます。
コントロールの間隔
12 文字の文字列を挿入する などの構文を使用して、結果文字列に挿入される文字列の幅 {0,12} を定義できます。 この場合、最初のオブジェクトの文字列表現は、12 文字のフィールドで右揃えになります。 (最初のオブジェクトの文字列表現の長さが 12 文字を超える場合、優先フィールドの幅は無視され、文字列全体が結果の文字列に挿入されます)。
次の例では、文字列 "Year" と一部の年の文字列を保持する 6 文字のフィールドと、文字列 "Population" と一部の母集団データを保持する 15 文字のフィールドを定義します。 文字は フィールド内で右揃えに配置されます。
array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
StringBuiler^ sb = gcnew StringBuilder();
sb->Append(String::Format("{0,6} {1,15}\n\n", "Year", "Population"));
for(int index = 0; index < years->Length; index++)
sb->AppendFormat("{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 };
var sb = new System.Text.StringBuilder();
sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
for (int index = 0; index < years.Length; index++)
sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));
Console.WriteLine(sb);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer = { 1025632, 1105967, 1148203 }
Dim sb As New StringBuilder()
sb.Append(String.Format("{0,6} {1,15}{2}{2}",
"Year", "Population", vbCrLf))
For index As Integer = 0 To years.Length - 1
sb.AppendFormat("{0,6} {1,15:N0}{2}",
years(index), population(index), vbCrLf)
Next
' Result:
' Year Population
'
' 2013 1,025,632
' 2014 1,105,967
' 2015 1,148,203
コントロールの配置
既定では、フィールドの幅を指定すると、文字列はフィールド内で右揃えになります。 フィールド内の文字列を左揃えするには、12 文字の左揃えフィールドを定義する場合など、フィールドの幅の前に負の符号を {0,-12} 付けます。
次の例は、ラベルとデータの両方を左揃えに配置する点を除き、前の例と似ています。
array<int>^ years = { 2013, 2014, 2015 };
array<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
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]);
Console.WriteLine($"\n{s}");
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer = { 1025632, 1105967, 1148203 }
Dim s As String = String.Format("{0,-10} {1,-10}{2}{2}",
"Year", "Population", vbCrLf)
For index As Integer = 0 To years.Length - 1
s += String.Format("{0,-10} {1,-10:N0}{2}",
years(index), population(index), vbCrLf)
Next
' Result:
' Year Population
'
' 2013 1,025,632
' 2014 1,105,967
' 2015 1,148,203
String.Format では、複合書式設定機能が使用されます。 詳細については、「複合書式指定」をご覧ください。
どのメソッドを呼び出しますか?
| 終了 | Call (英語の可能性あり) |
|---|---|
| 現在のカルチャの規則を使用して、1 つ以上のオブジェクトの書式を設定します。 | パラメーターを含むオーバーロードを除き、残りのオーバーロードには、パラメーターの後に 1 つ以上のオブジェクト パラメーター provider Format String が含まれます。 この理由から、呼び出すオーバーロードを決定 Format する必要が生じないので、 言語コンパイラは、引数リストに基づいて、パラメーターを持たなかったオーバーロードの中から適切な provider オーバーロードを選択します。 たとえば、引数リストに 5 つの引数がある場合、コンパイラは メソッドを呼び出 Format(String, Object[]) します。 |
| 特定のカルチャの規則を使用して、1 つ以上のオブジェクトの書式を設定します。 | パラメーターで始まる各オーバーロードの後には、パラメーターと 1 つ以上のオブジェクト Format provider String パラメーターが続きます。 この理由から、呼び出す特定のオーバーロードを決定 Format する必要が生じないので、 言語コンパイラは、引数リストに基づいて、パラメーターを持つオーバーロードの中から適切 provider なオーバーロードを選択します。 たとえば、引数リストに 5 つの引数がある場合、コンパイラは メソッドを呼び出 Format(IFormatProvider, String, Object[]) します。 |
| 実装または実装を使用して、カスタム書式設定 ICustomFormatter 操作を実行 IFormattable します。 | パラメーターを持つ 4 つのオーバーロード provider 。 コンパイラは、引数リストに基づいて、 パラメーターを持つオーバーロードの中から適切 provider なオーバーロードを選択します。 |
Format メソッドの概要
メソッドの各オーバーロードでは、複合書式指定機能を使用して、0 から始めるインデックス付きプレースホルダー (書式項目と呼ばれる) を複合書式指定 Format 文字列に含める。 実行時に、各書式項目は、パラメーター リスト内の対応する引数の文字列形式に置き換えられる。 引数の値が の場合、 null 書式項目は に置き換えられる String.Empty 。 たとえば、 メソッドの次の呼び出しには、3 つの書式指定項目 、、および を含む書式指定文字列と、3 つの項目を含む引数 Format(String, Object, Object, Object) {0} {1} {2} リストが含まれています。
using namespace System;
void main()
{
DateTime^ dat = gcnew 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.
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 output like the following:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
Dim dat As Date = #1/17/2012 9:30AM#
Dim city As String = "Chicago"
Dim temp As Integer = -16
Dim output As String = 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}", (Decimal) 126347.89);
var value = String.Format("{0,-10:C}", 126347.89m);
Console.WriteLine(value);
String.Format("{0,-10:C}", 126347.89d)
書式項目には、次の要素があります。
index
文字列形式を文字列内のこの位置に含める引数の 0 から始めるインデックス。 この引数が の null 場合、空の文字列が文字列内のこの位置に含まれます。
配置
任意。 引数が挿入されるフィールドの長さの合計と、右揃え (正の整数) か左揃え (負の整数) かを示す符号付き整数。 配置を省略 した 場合、対応する引数の文字列表現は、先頭または末尾のスペースがないフィールドに挿入されます。
配置の値が挿入される引数の長さより小さい場合、アラインメントは無視され、引数の文字列表現の長さがフィールドの幅として使用されます。
Formatstring
任意。 対応する引数の結果文字列の形式を指定する文字列。 formatString を省略すると、対応する引数のパラメーターなしメソッドが呼び出され、文字列 ToString 表現が生成されます。 formatString を指定する場合、 書式項目によって参照される引数は インターフェイスを実装する必要 IFormattable があります。 書式指定文字列をサポートする型は次のとおりです。
すべての整数型と浮動小数点型。 (「 標準の数値書式指定文字列 」および「 カスタム数値書式指定文字列」を参照してください)。
DateTime および DateTimeOffset。 (「 標準の日付と時刻の書式指定文字列 」および「 カスタム日時書式指定文字列」を参照してください)。
すべての列挙型。 (「 列挙型書式指定文字列」を参照してください)。
TimeSpan 値。 (「 標準の Timespan 書式指定文字列 」および「 カスタム TimeSpan 書式指定文字列」を参照してください)。
GUID。 (メソッドを参照してください Guid.ToString(String) )。
ただし、カスタム型で IFormattable は、既存の型の実装を実装または拡張できることに注意して IFormattable ください。
次の例では、引数と引数を使用して、 alignment formatString 書式設定された出力を生成します。
using namespace System;
void main()
{
// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
array<Tuple<String^, DateTime, int, DateTime, int>^>^ cities = gcnew array<Tuple<String^, DateTime, int, DateTime, int>^>
{ gcnew Tuple<String^, DateTime, int, DateTime, int>("Los Angeles", DateTime(1940, 1, 1), 1504277,
DateTime(1950, 1, 1), 1970358),
gcnew Tuple<String^, DateTime, int, DateTime, int>("New York", DateTime(1940, 1, 1), 7454995,
DateTime(1950, 1, 1), 7891957),
gcnew Tuple<String^, DateTime, int, DateTime, int>("Chicago", DateTime(1940, 1, 1), 3396808,
DateTime(1950, 1, 1), 3620962),
gcnew Tuple<String^, DateTime, int, DateTime, int>("Detroit", DateTime(1940, 1, 1), 1623452,
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;
for each (Tuple<String^, DateTime, int, DateTime, int>^ 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 %
// 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
var header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
"City", "Year", "Population", "Change (%)");
Console.WriteLine(header);
foreach (var city in cities) {
var 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 %
Module Example
Public Sub Main()
' Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Dim cities() = _
{ Tuple.Create("Los Angeles", #1/1/1940#, 1504277, #1/1/1950#, 1970358),
Tuple.Create("New York", #1/1/1940#, 7454995, #1/1/1950#, 7891957),
Tuple.Create("Chicago", #1/1/1940#, 3396808, #1/1/1950#, 3620962),
Tuple.Create("Detroit", #1/1/1940#, 1623452, #1/1/1950#, 1849568) }
' Display header
Dim header As String = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}",
"City", "Year", "Population", "Change (%)")
Console.WriteLine(header)
Console.WriteLine()
For Each city In cities
Dim 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)/city.Item3)
Console.WriteLine(output)
Next
End Sub
End Module
' 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 ます。
引数がの場合、
nullメソッドは結果の文字列にを挿入し String.Empty ます。 Null 引数のの処理について心配する必要はありません NullReferenceException 。オーバーロードを呼び出し、 Format(IFormatProvider, String, Object[])
providerオブジェクトの実装が null 以外の実装を返した場合、 IFormatProvider.GetFormat ICustomFormatter 引数はメソッドに渡され ICustomFormatter.Format(String, Object, IFormatProvider) ます。 書式指定項目に formatString 引数が含まれている場合は、メソッドに最初の引数として渡されます。 ICustomFormatter実装が使用可能で、null 以外の文字列を生成する場合は、その文字列が引数の文字列形式として返されます。それ以外の場合は、次の手順が実行されます。引数がインターフェイスを実装している場合は、 IFormattable その IFormattable.ToString 実装が呼び出されます。
ToStringオーバーライドするか、基底クラスの実装から継承する、引数のパラメーターなしのメソッドが呼び出されます。
メソッドへの呼び出しをインターセプトし、 ICustomFormatter.Format 複合書式指定文字列の書式指定項目ごとにメソッドが書式指定メソッドに渡す情報を確認できる例については Format 、「 例: インターセプトプロバイダーとローマ数字フォーマッタ」を参照してください。
詳細については、「複合書式指定」の「処理順序」セクションを参照してください。
同じインデックスを持つ項目を書式設定する
Format FormatException インデックス項目のインデックスが引数リスト内の引数の数以上の場合、メソッドは例外をスローします。 ただし、 format 複数の書式指定項目のインデックスが同じである限り、には引数よりも多くの書式項目を含めることができます。 Format(String, Object)次の例のメソッドの呼び出しでは、引数リストに1つの引数がありますが、書式指定文字列には2つの書式項目が含まれています。1つは数値の10進値を表示し、もう1つは16進数値を表示します。
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
Module Example
Public Sub Main()
Dim values() As Short = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue }
Console.WriteLine("{0,10} {1,10}", "Decimal", "Hex")
Console.WriteLine()
For Each value As Short In values
Dim formatString As String = String.Format("{0,10:G}: {0,10:X}", value)
Console.WriteLine(formatString)
Next
End Sub
End Module
' The example displays the following output:
' Decimal Hex
'
' -32768: 8000
' -27: FFE5
' 0: 0
' 1042: 412
' 32767: 7FFF
形式とカルチャ
通常、引数リスト内のオブジェクトは、現在のカルチャの規則を使用して文字列形式に変換されます。これは、プロパティによって返され CultureInfo.CurrentCulture ます。 この動作を制御するには、パラメーターを含むのオーバーロードのいずれかを呼び出し Format provider ます。 providerパラメーターは、 IFormatProvider 書式設定プロセスをモデレートするために使用されるカスタムおよびカルチャ固有の書式設定情報を提供するの実装です。
IFormatProviderインターフェイスには、1つのメンバーがあります GetFormat 。これは、書式設定情報を提供するオブジェクトを返す役割を担います。 .NET には、 IFormatProvider カルチャ固有の書式設定を提供する3つの実装があります。
CultureInfo. この GetFormat メソッドは、 NumberFormatInfo 数値を書式設定するためのカルチャ固有のオブジェクト、および DateTimeFormatInfo 日付と時刻の値を書式設定するためのカルチャ固有のオブジェクトを返します。
DateTimeFormatInfo。日付と時刻の値のカルチャ固有の書式設定に使用されます。 その GetFormat メソッドは、それ自体を返します。
NumberFormatInfo。数値のカルチャ固有の書式設定に使用されます。 その GetFormat プロパティは、それ自体を返します。
カスタムの書式設定操作
また、型のパラメーターを持つメソッドの任意のオーバーロードを呼び出して、 Format provider カスタムの IFormatProvider 書式設定操作を実行することもできます。 たとえば、整数を識別番号として、または電話番号として書式設定できます。 カスタム書式設定を実行するには、 provider 引数にインターフェイスとインターフェイスの両方を実装する必要があり IFormatProvider ICustomFormatter ます。 メソッドに Format ICustomFormatter 引数として実装が渡されると、 provider Format メソッドはその IFormatProvider.GetFormat 実装を呼び出し、型のオブジェクトを要求し ICustomFormatter ます。 次に、返されたオブジェクトのメソッドを呼び出して、 ICustomFormatter Format 渡された複合文字列の各書式項目を書式設定します。
カスタム書式指定ソリューションの提供の詳細については、「 方法: カスタム数値書式プロバイダーを定義して使用 する」および「」を参照してください ICustomFormatter 。 整数を書式設定されたカスタム数値に変換する例については、「 例: カスタム書式指定操作」を参照してください。 符号なしバイトをローマ数字に変換する例については、「 例: インターセプトプロバイダーとローマ数字フォーマッタ」を参照してください。
例: カスタム書式設定操作
この例では、整数値を、"x-xxxxx-xx" の形式で顧客アカウント番号として書式設定する書式プロバイダーを定義します。
using namespace System;
ref class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public:
virtual Object^ GetFormat(Type^ formatType)
{
if (formatType == ICustomFormatter::typeid)
return this;
else
return nullptr;
}
virtual String^ Format(String^ format,
Object^ arg,
IFormatProvider^ formatProvider)
{
if (! this->Equals(formatProvider))
{
return nullptr;
}
else
{
if (String::IsNullOrEmpty(format))
format = "G";
String^ customerString = arg->ToString();
if (customerString->Length < 8)
customerString = customerString->PadLeft(8, '0');
format = format->ToUpper();
if (format == L"G")
return customerString->Substring(0, 1) + "-" +
customerString->Substring(1, 5) + "-" +
customerString->Substring(6);
else if (format == L"S")
return customerString->Substring(0, 1) + "/" +
customerString->Substring(1, 5) + "/" +
customerString->Substring(6);
else if (format == L"P")
return customerString->Substring(0, 1) + "." +
customerString->Substring(1, 5) + "." +
customerString->Substring(6);
else
throw gcnew FormatException(
String::Format("The '{0}' format specifier is not supported.", format));
}
}
};
void main()
{
int acctNumber = 79203159;
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:G}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:S}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:P}", acctNumber));
try {
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:X}", acctNumber));
}
catch (FormatException^ e) {
Console::WriteLine(e->Message);
}
}
// 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.
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.
Module TestFormatter
Public Sub Main()
Dim acctNumber As Integer = 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 e As FormatException
Console.WriteLine(e.Message)
End Try
End Sub
End Module
Public Class CustomerFormatter : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(type As Type) As Object _
Implements IFormatProvider.GetFormat
If type Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, _
arg As Object, _
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
If Not Me.Equals(formatProvider) Then
Return Nothing
Else
If String.IsNullOrEmpty(fmt) Then fmt = "G"
Dim customerString As String = arg.ToString()
if customerString.Length < 8 Then _
customerString = customerString.PadLeft(8, "0"c)
Select Case fmt
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)
Case Else
Throw New FormatException( _
String.Format("The '{0}' format specifier is not supported.", fmt))
End Select
End If
End Function
End Class
' 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.
例: インターセプトプロバイダーとローマ数字のフォーマッタ
この例では、 ICustomFormatter 次の2つの処理を行うためのインターフェイスとインターフェイスを実装するカスタム書式プロバイダーを定義し IFormatProvider ます。
実装に渡されたパラメーターが表示され ICustomFormatter.Format ます。 これにより、 Format(IFormatProvider, String, Object[]) 書式設定を試行した各オブジェクトのカスタム書式設定の実装に、メソッドが渡すパラメーターを確認できます。 これは、アプリケーションをデバッグしているときに便利です。
書式設定されるオブジェクトが、"R" 標準書式指定文字列を使用して書式設定される符号なしバイト値の場合、カスタムフォーマッタは数値をローマ数字として書式設定します。
using namespace System;
using namespace System::Globalization;
ref class InterceptProvider : IFormatProvider, ICustomFormatter
{
public:
virtual Object^ GetFormat(Type^ formatType)
{
if (formatType == ICustomFormatter::typeid)
return this;
else
return nullptr;
}
virtual String^ Format(String^ format, Object^ obj, IFormatProvider^ provider)
{
// Display information about method call.
String^ formatString = format != nullptr ? format : "<null>";
Console::WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider, obj != nullptr ? obj : "<null>", formatString);
if (obj == nullptr) return String::Empty;
// If this is a byte and the "R" format string, format it with Roman numerals.
if (obj->GetType() == Byte::typeid && 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, remainder);
if (result > 0)
returnString = gcnew String('C', result);
value = (Byte) remainder;
// Get the 50s digit
result = Math::DivRem(value, 50, remainder);
if (result == 1)
returnString += "L";
value = (Byte) remainder;
// Get the tens digit.
result = Math::DivRem(value, 10, remainder);
if (result > 0)
returnString += gcnew String('X', result);
value = (Byte) remainder;
// Get the fives digit.
result = Math::DivRem(value, 5, remainder);
if (result > 0)
returnString += "V";
value = (Byte) remainder;
// Add the ones digit.
if (remainder > 0)
returnString += gcnew 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->GetType() == IFormattable::typeid)
return ((IFormattable^) obj)->ToString(format, CultureInfo::CurrentCulture);
else
return obj->ToString();
}
};
void main()
{
int n = 10;
double value = 16.935;
DateTime day = DateTime::Now;
InterceptProvider^ provider = gcnew 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
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.GetType().Name, 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
Imports System.Globalization
Public Class InterceptProvider : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, obj As Object, provider As IFormatProvider) As String _
Implements ICustomFormatter.Format
Dim formatString As String = If(fmt IsNot Nothing, fmt, "<null>")
Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider, If(obj IsNot Nothing, obj, "<null>"), formatString)
If obj Is Nothing Then Return String.Empty
' If this is a byte and the "R" format string, format it with Roman numerals.
If TypeOf(obj) Is Byte AndAlso formatString.ToUpper.Equals("R") Then
Dim value As Byte = CByte(obj)
Dim remainder As Integer
Dim result As Integer
Dim returnString As String = String.Empty
' Get the hundreds digit(s)
result = Math.DivRem(value, 100, remainder)
If result > 0 Then returnString = New String("C"c, result)
value = CByte(remainder)
' Get the 50s digit
result = Math.DivRem(value, 50, remainder)
If result = 1 Then returnString += "L"
value = CByte(remainder)
' Get the tens digit.
result = Math.DivRem(value, 10, remainder)
If result > 0 Then returnString += New String("X"c, result)
value = CByte(remainder)
' Get the fives digit.
result = Math.DivRem(value, 5, remainder)
If result > 0 Then returnString += "V"
value = CByte(remainder)
' Add the ones digit.
If remainder > 0 Then returnString += New String("I"c, remainder)
' Check whether we have too many X characters.
Dim pos As Integer = returnString.IndexOf("XXXX")
If pos >= 0 Then
Dim xPos As Integer = returnString.IndexOf("L")
If xPos >= 0 And xPos = pos - 1 Then
returnString = returnString.Replace("LXXXX", "XC")
Else
returnString = returnString.Replace("XXXX", "XL")
End If
End If
' Check whether we have too many I characters
pos = returnString.IndexOf("IIII")
If pos >= 0 Then
If returnString.IndexOf("V") >= 0 Then
returnString = returnString.Replace("VIIII", "IX")
Else
returnString = returnString.Replace("IIII", "IV")
End If
End If
Return returnString
End If
' Use default for all other formatting.
If obj Is GetType(IFormattable)
Return CType(obj, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
Else
Return obj.ToString()
End If
End Function
End Class
Module Example
Public Sub Main()
Dim n As Integer = 10
Dim value As Double = 16.935
Dim day As DateTime = Date.Now
Dim provider As New InterceptProvider()
Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}", n, value, day))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0}: {1:F}", "Today",
CType(Date.Now.DayOfWeek, DayOfWeek)))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n",
CByte(2), CByte(12), CByte(199)))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}",
CByte(2), CByte(12), CByte(199)))
End Sub
End Module
' 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
文字列。 Q & A を書式設定します。
メソッドの呼び出しに対して文字列補間を推奨するのはなぜ String.Format ですか。
文字列補間は次のとおりです。
より柔軟です。 複合書式指定をサポートするメソッドの呼び出しを必要とせずに、任意の文字列で使用できます。 それ以外の場合は、 Format メソッド、またはやなどの複合書式指定をサポートする別のメソッドを呼び出す必要があり Console.WriteLine StringBuilder.AppendFormat ます。
より読みやすくなります。 文字列に挿入する式は、引数リストではなく、挿入式に含まれるので、補間文字列の方がコードや読み取りがはるかに簡単になります。 より読みやすくなっているため、補間文字列は複合書式指定メソッドの呼び出しだけでなく、より簡潔で明確なコードを生成するために文字列連結操作でも使用できます。
次の2つのコード例は、文字列の連結と複合書式指定メソッドの呼び出しに対する補間文字列の優位性を示しています。 次の例では、複数の文字列連結演算を使用して、詳細なコードと読み取り専用のコードを作成します。
string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = names[0] + ", " + names[1] + ", " + names[2] + ", " +
names[3] + ", " + names[4] + ", " + names[5] + ", " +
names[6];
output += "\n";
var date = DateTime.Now;
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.",
date, date.DayOfWeek);
Console.WriteLine(output);
// The example displays the following output:
// Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
// It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Module Example
Public Sub Main()
Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
Dim output = names(0) + ", " + names(1) + ", " + names(2) + ", " +
names(3) + ", " + names(4) + ", " + names(5) + ", " +
names(6)
output += vbCrLf
Dim dat = DateTime.Now
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.",
dat, dat.DayOfWeek)
Console.WriteLine(output)
End Sub
End Module
' The example displays the following output:
' Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
' It is 10:29 AM on 1/8/2018. The day of the week is Monday.
これに対し、次の例では、挿入文字列を使用して、文字列連結ステートメントと前の例のメソッドの呼び出しよりも、より明確で簡潔なコードを生成し Format ます。
string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = $"{names[0]}, {names[1]}, {names[2]}, {names[3]}, {names[4]}, " +
$"{names[5]}, {names[6]}";
var date = DateTime.Now;
output += $"\nIt is {date:t} on {date:d}. The day of the week is {date.DayOfWeek}.";
Console.WriteLine(output);
// The example displays the following output:
// Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
// It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Module Example
Public Sub Main()
Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
Dim output = $"{names(0)}, {names(1)}, {names(2)}, {names(3)}, {names(4)}, " +
$"{names(5)}, {names(6)}"
Dim dat = DateTime.Now
output += $"{vbCrLf}It is {dat:t} on {dat:d}. The day of the week is {dat.DayOfWeek}."
Console.WriteLine(output)
End Sub
End Module
' The example displays the following output:
' Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
' It is 10:29 AM on 1/8/2018. The day of the week is Monday.
書式項目と共に使用できる定義済みの書式指定文字列の一覧はどこで確認できますか。
すべての整数型と浮動小数点型については、「 標準の数値書式指定文字列 」および「 カスタム数値書式指定文字列」を参照してください。
日付と時刻の値については、「 標準の日付と時刻の書式指定文字列 」および「 カスタム日時書式指定文字列」を参照してください。
列挙値については、「 列挙型書式指定文字列」を参照してください。
値につい TimeSpan ては、「 標準の Timespan 書式指定文字列 」および「 カスタム TimeSpan 書式指定文字列」を参照してください。
値については、 Guid リファレンスページの「解説」を参照してください Guid.ToString(String) 。
書式項目を置き換える結果文字列の配置を制御操作方法には
書式項目の一般的な構文は次のとおりです。
{index[,alignment][: formatString]}
alignment は、フィールドの幅を定義する符号付き整数です。 この値が負の場合、フィールド内のテキストは左揃えになります。 正の場合、テキストは右に固定されます。
小数点区切り文字の後に桁数を制御操作方法には、
"D" を除くすべての 標準の数値書式指定文字列 (整数のみで使用)、"G"、"R"、および "X" を使用すると、結果文字列の小数点以下の桁数を定義する精度指定子を使用できます。 次の例では、標準の数値書式指定文字列を使用して、結果文字列の小数点以下桁数を制御します。
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 output like the following:
// $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 %
Module Example
Public Sub Main()
Dim values() As Object = { 1603, 1794.68235, 15436.14 }
Dim result As String
For Each value In values
result = String.Format("{0,12:C2} {0,12:E3} {0,12:F4} {0,12:N3} {1,12:P2}",
value, CDbl(value) / 10000)
Console.WriteLine(result)
Console.WriteLine()
Next
End Sub
End Module
' 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 %
カスタム数値書式指定文字列を使用している場合は、次の例に示すように、"0" 書式指定子を使用して、結果文字列の小数点以下の桁数を制御します。
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
Module Example
Public Sub Main()
Dim value As Decimal = 16309.5436d
Dim result As String = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}",
value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 16309.54360 16,309.54 16309.544
整数の桁数を制御操作方法には
既定では、書式設定操作には0以外の整数の数字のみが表示されます。 整数を書式設定する場合は、"D" および "X" の標準書式指定文字列で精度指定子を使用して、桁数を制御できます。
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
Module Example
Public Sub Main()
Dim value As Integer = 1326
Dim result As String = String.Format("{0,10:D6} {0,10:X8}", value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 001326 0000052E
次の例に示すように、"0" カスタム数値書式指定子を使用して、整数または浮動小数点数を先行ゼロで埋め込んで、指定された数の整数を含む結果文字列を生成することができます。
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
Module Example
Public Sub Main()
Dim value As Integer = 16342
Dim result As String = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}",
value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 00016342 00016342.000 0,000,016,342.0
[書式] の一覧に含めることができる項目の数はいくつですか。
実際の制限はありません。 メソッドの2番目のパラメーターに Format(IFormatProvider, String, Object[]) は属性がタグ付けされます ParamArrayAttribute 。これにより、区切り記号付きリストまたはオブジェクト配列を書式リストとして含めることができます。
結果の文字列にリテラルの中かっこ ("{" および "}") を含める操作方法
たとえば、次のメソッド呼び出しによって例外がスローされないようにするには、どうすればよい FormatException でしょうか。
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)
1つの左中かっこまたは右中かっこは、書式指定項目の先頭または末尾として常に解釈されます。 文字どおりに解釈されるようにするには、エスケープする必要があります。 かっこをエスケープするには、次のメソッド呼び出しのように、別の中かっこ ("{" および "}" ではなく "{{" および "}}") を追加します。
string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose);
Console.WriteLine(result);
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose)
ただし、エスケープされた中かっこも簡単に解釈できます。 次の例に示すように、書式設定の一覧に中かっこを含め、書式項目を使用して結果の文字列に挿入することをお勧めします。
string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}");
Console.WriteLine(result);
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}")
FormatException メソッドを呼び出すと、そのような例外がスローされるのはなぜですか。
例外の最も一般的な原因として、書式項目のインデックスが [書式] リストのオブジェクトに対応していないことが挙げられます。 通常、これは、書式項目のインデックスに番号が付けられていないか、[書式] ボックスの一覧にオブジェクトが含まれていないことを示します。 エスケープされていない左または右の中かっこ文字を含めようとすると、もスローさ FormatException れます。 場合によっては、例外が発生することがあります。たとえば、一般的な誤りは、"{" (左中かっこ) ではなく "[" (左角かっこ) を誤って間違えてしまうことです。
Format (IFormatProvider, System.string, System.object []) メソッドがパラメーター配列をサポートしている場合、配列を使用すると、コードで例外がスローされるのはなぜですか。
たとえば、次のコードでは例外がスローされ FormatException ます。
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);
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim numbers(3) As Integer
Dim total As Integer = 0
For ctr = 0 To 2
Dim number As Integer = rnd.Next(1001)
numbers(ctr) = number
total += number
Next
numbers(3) = total
Console.WriteLine("{0} + {1} + {2} = {3}", numbers)
End Sub
End Module
これは、コンパイラのオーバーロードの解決に問題があります。 コンパイラは整数の配列をオブジェクト配列に変換できないので、整数配列を1つの引数として扱います。そのため、メソッドを呼び出し Format(String, Object) ます。 この例外がスローされるのは、書式指定項目が4つありますが、書式一覧に項目が1つしかないためです。
Visual Basic も C# も整数配列をオブジェクト配列に変換できないため、メソッドを呼び出す前に、変換を自分で実行する必要があり Format(String, Object[]) ます。 次の例で 1 つの実装を示します。
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);
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim numbers(3) As Integer
Dim total As Integer = 0
For ctr = 0 To 2
Dim number As Integer = rnd.Next(1001)
numbers(ctr) = number
total += number
Next
numbers(3) = total
Dim values(numbers.Length - 1) As Object
numbers.CopyTo(values, 0)
Console.WriteLine("{0} + {1} + {2} = {3}", values)
End Sub
End Module
Format(String, Object)
文字列の 1 つ以上の書式項目を、指定されたオブジェクトの文字列表記に置換します。
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
パラメーター
- arg0
- Object
書式指定するオブジェクト。
戻り値
書式項目が format の文字列形式に置換された arg0 のコピー。
例外
format が nullです。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドは、 複合書式指定機能 を使用して、式の値を文字列形式に変換し、その表現を文字列に埋め込みます。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、1 つ以上の書式項目を含む、複合書式指定文字列を指定してメソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
例: 1 つの引数の書式設定
次の例では、メソッドを使用して、 Format(String, Object) 文字列の途中に個別の年齢を埋め込みます。
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.
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.
こちらもご覧ください
- .NET での型の書式設定
- 複合書式指定
- 標準の日時書式指定文字列
- カスタム日時書式指定文字列
- 標準の数値書式指定文字列
- カスタム数値形式文字列
- 標準 TimeSpan 書式指定文字列
- カスタム時間間隔書式指定文字列
- 列挙型書式指定文字列
適用対象
Format(String, Object[])
指定した文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列形式に置換します。
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
パラメーター
- args
- Object[]
0 個以上の書式設定対象オブジェクトを含んだオブジェクト配列。
戻り値
書式項目が args の対応するオブジェクトの文字列表記に置換された format のコピー。
例外
format または args が null です。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドは、 複合書式指定機能 を使用して、4つ以上の式の値を文字列形式に変換し、それらの表現を文字列に埋め込みます。 argsパラメーターは属性でマークされているため、 System.ParamArrayAttribute オブジェクトを個々の引数として、または配列としてメソッドに渡すことができ Object ます。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、1 つ以上の書式項目を含む、複合書式指定文字列を指定してメソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
例: 3 つ以上の引数を書式設定する
この例では、特定の日付の高および低気温に関するデータを格納する文字列を作成します。 複合書式指定文字列には、C# の例では5つの書式項目、Visual Basic の例では6個の書式項目があります。 2つの書式項目は、対応する値の文字列表現の幅を定義し、最初の書式指定項目には標準の日時書式指定文字列も含まれます。
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)
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)
また、オブジェクトを引数リストとしてではなく配列として渡すこともできます。
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
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
こちらもご覧ください
- .NET での型の書式設定
- 複合書式指定
- 標準の日時書式指定文字列
- カスタム日時書式指定文字列
- 標準の数値書式指定文字列
- カスタム数値形式文字列
- 標準 TimeSpan 書式指定文字列
- カスタム時間間隔書式指定文字列
- 列挙型書式指定文字列
適用対象
Format(IFormatProvider, String, Object)
指定した文字列の 1 つまたは複数の書式項目を、対応するオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。
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
パラメーター
- provider
- IFormatProvider
カルチャ固有の書式情報を提供するオブジェクト。
- arg0
- Object
書式指定するオブジェクト。
戻り値
書式項目が format の文字列形式に置換された arg0 のコピー。
例外
format が nullです。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドは、 複合書式指定機能 を使用して、式の値を文字列形式に変換し、その表現を文字列に埋め込みます。 変換を実行する場合、メソッドはカルチャに依存した書式設定またはカスタムフォーマッタを使用します。 メソッドは、 arg0 Tostring (IFormatProvider) メソッドを呼び出すことによって文字列形式に変換します。または、オブジェクトの対応する書式指定項目に Tostring (string, IFormatProvider) メソッドを呼び出すことによって書式指定文字列が含まれている場合は、を呼び出します。 これらのメソッドが存在しない場合は、オブジェクトのパラメーターなしの ToString メソッドを呼び出します。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、カルチャに依存した書式設定またはカスタム書式設定および 1 つ以上の書式項目を含む複合書式指定文字列を提供するオブジェクトを使用して、メソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
適用対象
Format(IFormatProvider, String, Object[])
文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列表記に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。
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
パラメーター
- provider
- IFormatProvider
カルチャ固有の書式情報を提供するオブジェクト。
- args
- Object[]
0 個以上の書式設定対象オブジェクトを含んだオブジェクト配列。
戻り値
書式項目が args の対応するオブジェクトの文字列表記に置換された format のコピー。
例外
format または args が null です。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドは、複合書式 指定機能を 使用して、4 つ以上の式を文字列形式に変換し、それらの表現を文字列に埋め込む方法です。 変換を実行する場合、メソッドはカルチャに依存する書式設定またはカスタム 書式指定子を使用します。 メソッドは、ToString(IFormatProvider) メソッドを呼び出すことによって各引数を文字列形式に変換します。または、オブジェクトの対応する書式項目に書式指定文字列が含まれる場合は Object 、ToString(String,IFormatProvider) メソッドを呼び出します。 これらのメソッドが存在しない場合は、オブジェクトのパラメーターのない ToString メソッド を呼び出 します。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、カルチャに依存した書式設定またはカスタム書式設定および 1 つ以上の書式項目を含む複合書式指定文字列を提供するオブジェクトを使用して、メソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
例: カルチャに依存する書式設定
この例では、 メソッドを使用して、いくつかの異なるカルチャを使用して、一部の日付と時刻の値と数値の Format(IFormatProvider, String, Object[]) 文字列表現を表示します。
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
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
こちらもご覧ください
- DateTimeFormatInfo
- ICustomFormatter
- IFormatProvider
- NumberFormatInfo
- .NET での型の書式設定
- 複合書式指定
- 標準の日時書式指定文字列
- カスタム日時書式指定文字列
- 標準の数値書式指定文字列
- カスタム数値形式文字列
- 標準 TimeSpan 書式指定文字列
- カスタム時間間隔書式指定文字列
- 列挙型書式指定文字列
適用対象
Format(String, Object, Object)
文字列の書式項目を、指定した 2 つのオブジェクトの文字列形式に置換します。
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
パラメーター
- arg0
- Object
1 番目に書式設定するオブジェクト。
- arg1
- Object
2 番目に書式設定するオブジェクト。
戻り値
書式項目が arg0 と arg1 の文字列形式に置換された format のコピー。
例外
format が nullです。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドでは、 複合書式指定 機能を使用して、2 つの式の値を文字列形式に変換し、それらの表現を文字列に埋め込まれます。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、1 つ以上の書式項目を含む、複合書式指定文字列を指定してメソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
例: 2 つの引数の書式を設定する
この例では、 Format(String, Object, Object) メソッドを使用して、ジェネリック オブジェクトに格納されている時間と温度のデータを表示 Dictionary<TKey,TValue> します。 書式指定するオブジェクトは 2 つのみですが、書式指定文字列には 3 つの書式項目があります。 これは、リスト内の最初のオブジェクト (日付と時刻の値) が 2 つの書式項目によって使用されるためです。1 つ目の書式項目は時刻を表示し、2 番目のオブジェクトは日付を表示します。
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
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
こちらもご覧ください
- .NET での型の書式設定
- 複合書式指定
- 標準の日時書式指定文字列
- カスタム日時書式指定文字列
- 標準の数値書式指定文字列
- カスタム数値形式文字列
- 標準 TimeSpan 書式指定文字列
- カスタム時間間隔書式指定文字列
- 列挙型書式指定文字列
適用対象
Format(IFormatProvider, String, Object, Object)
文字列の書式項目を、指定した 2 つのオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式情報が指定されます。
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
パラメーター
- provider
- IFormatProvider
カルチャ固有の書式情報を提供するオブジェクト。
- arg0
- Object
1 番目に書式設定するオブジェクト。
- arg1
- Object
2 番目に書式設定するオブジェクト。
戻り値
書式項目が arg0 と arg1 の文字列形式に置換された format のコピー。
例外
format が nullです。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドは、複合 書式指定 機能を使用して、2 つの式を文字列形式に変換し、それらの表現を文字列に埋め込む方法です。 変換を実行する場合、メソッドはカルチャに依存する書式設定またはカスタム 書式指定子を使用します。 メソッドは、ToString(IFormatProvider) メソッドを呼び出すことによって各引数を文字列形式に変換します。または、オブジェクトの対応する書式項目に書式指定文字列が含まれる場合は Object 、ToString(String,IFormatProvider) メソッドを呼び出します。 これらのメソッドが存在しない場合は、オブジェクトのパラメーターのない ToString メソッド を呼び出 します。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、カルチャに依存した書式設定またはカスタム書式設定および 1 つ以上の書式項目を含む複合書式指定文字列を提供するオブジェクトを使用して、メソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
適用対象
Format(String, Object, Object, Object)
文字列の書式項目を、指定した 3 つのオブジェクトの文字列形式に置換します。
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
パラメーター
- arg0
- Object
1 番目に書式設定するオブジェクト。
- arg1
- Object
2 番目に書式設定するオブジェクト。
- arg2
- Object
3 番目に書式設定するオブジェクト。3 番目に書式設定するオブジェクト。
戻り値
書式項目が format、arg0、および arg1 の文字列形式に置換された arg2 のコピー。
例外
format が nullです。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドでは、 複合書式指定 機能を使用して、3 つの式の値を文字列形式に変換し、それらの表現を文字列に埋め込まれます。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、1 つ以上の書式項目を含む、複合書式指定文字列を指定してメソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。
例: 3 つの引数を書式設定する
この例では、 メソッドを使用して、2 つの整数値を持つブール演算の結果を示 Format(String, Object, Object, Object) And す文字列を作成します。 書式指定文字列には 6 つの書式項目が含まれていますが、メソッドのパラメーター リストには 3 つの項目しか含めないので、各項目は 2 つの異なる方法で書式設定されます。
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)
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)
こちらもご覧ください
適用対象
Format(IFormatProvider, String, Object, Object, Object)
文字列の書式項目を、指定した 3 つのオブジェクトの文字列形式に置換します。 パラメーターにより、カルチャに固有の書式設定情報を指定します。
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
パラメーター
- provider
- IFormatProvider
カルチャ固有の書式情報を提供するオブジェクト。
- arg0
- Object
1 番目に書式設定するオブジェクト。
- arg1
- Object
2 番目に書式設定するオブジェクト。
- arg2
- Object
3 番目に書式設定するオブジェクト。3 番目に書式設定するオブジェクト。
戻り値
書式項目が format、arg0、および arg1 の文字列形式に置換された arg2 のコピー。
例外
format が nullです。
注釈
重要
String.Format メソッドを呼び出す、あるいは 複合書式指定文字列を使用する代わりに、お使いの言語でサポートされている場合、挿入文字列 を使用できます。 挿入文字列は、挿入式 が含まれている文字列です。 各挿入式は式の値によって解かれ、文字列が割り当てられるとき、結果文字列に含まれます。 詳細については、文字列補間 (C# リファレンス) および補間文字列 (Visual Basic リファレンス) に関するページを参照してください。
このメソッドでは、複合 書式指定機能を 使用して、3 つの式を文字列形式に変換し、それらの表現を文字列に埋め込まれます。 変換を実行する場合、メソッドはカルチャに依存する書式設定またはカスタム 書式指定子を使用します。 メソッドは、ToString(IFormatProvider) メソッドを呼び出すことによって各引数を文字列形式に変換します。または、オブジェクトの対応する書式項目に書式指定文字列が含まれる場合は Object 、ToString(String,IFormatProvider) メソッドを呼び出します。 これらのメソッドが存在しない場合は、オブジェクトのパラメーターのない ToString メソッド を呼び出 します。
ただし、String.Format メソッドの呼び出し時に、呼び出す特定のオーバーロードに焦点を当てる必要はありません。 代わりに、カルチャに依存した書式設定またはカスタム書式設定および 1 つ以上の書式項目を含む複合書式指定文字列を提供するオブジェクトを使用して、メソッドを呼び出すことができます。 各書式項目を数値インデックスに割り当てます。最初のインデックスは 0 から始まります。 最初の文字列だけでなく、メソッド呼び出しには、インデックス値と同じ数の追加引数が必要です。 たとえば、書式項目のインデックスが 0 と 1 の文字列には 2 個の引数が必要です。インデックスが 0 から 5 の場合は、6 個の引数が必要です。 その後、言語コンパイラは、String.Format メソッドの特定のオーバーロードに対するメソッド呼び出しを解決します。
String.Format メソッドの使用に関する詳細なドキュメントについては、String.Format メソッドの概要と 呼び出すメソッドに関するトピックを参照してください。