文字列.PadLeft() / PadRight()
| 対応: | C# 1.0(2002) |
|---|
文字列を指定した長さになるよう左側に文字を埋める『PadLeft()』、右側に文字を埋める『PadRight()』メソッドと、書式指定文字列を作成する『string.Format()』メソッドです。
構文
// 左側に空白(または指定文字)を埋めて、totalWidth の長さにした文字列を返します。 文字列.PadLeft(int totalWidth) 文字列.PadLeft(int totalWidth, char paddingChar) // 右側に空白(または指定文字)を埋めて、totalWidth の長さにした文字列を返します。 文字列.PadRight(int totalWidth) 文字列.PadRight(int totalWidth, char paddingChar) // 書式指定文字列にパラメーターを埋め込んだ文字列を返します。 string.Format(string format, object arg0, ...)
メソッド一覧
| メソッド | 概要 |
|---|---|
| PadLeft(int totalWidth) | 左側に空白を埋めて totalWidth 文字の文字列を返します。元の文字列が totalWidth 以上の長さの場合は変更されません。 |
| PadLeft(int totalWidth, char paddingChar) | 左側に paddingChar を埋めて totalWidth 文字の文字列を返します。 |
| PadRight(int totalWidth) | 右側に空白を埋めて totalWidth 文字の文字列を返します。 |
| PadRight(int totalWidth, char paddingChar) | 右側に paddingChar を埋めて totalWidth 文字の文字列を返します。 |
| string.Format(string format, ...) | {0}、{1} などのプレースホルダーを引数の値で置き換えた文字列を返します。 |
サンプルコード
Program.cs
using System;
// PadLeft() で右寄せ表示(数値の桁揃え)をします。
for (int i = 1; i <= 5; i++)
{
string row = i.ToString().PadLeft(3);
Console.WriteLine(row);
}
// PadLeft() でゼロ埋めをします。
string code = "42".PadLeft(6, '0');
Console.WriteLine(code); // 000042
// PadRight() で左寄せ表示をします。
string[] members = { "八神庵", "草薙京", "テリー・ボガード" };
int[] scores = { 95, 88, 72 };
for (int i = 0; i < members.Length; i++)
{
Console.WriteLine(members[i].PadRight(8) + scores[i] + "点");
}
// string.Format() で書式を指定します。
string message = string.Format("{0}さんのスコアは{1}点です。", "八神庵", 95);
Console.WriteLine(message); // 八神庵さんのスコアは95点です。
// 数値の書式指定(小数点2桁など)もできます。
double ratio = 0.1567;
Console.WriteLine(string.Format("割引率: {0:P1}", ratio)); // 割引率: 15.7%
dotnet script string_padleft_padright.csx 1 2 3 4 5 000042 八神庵 95点 草薙京 88点 テリー・ボガード72点 八神庵さんのスコアは95点です。 割引率: 15.7%
概要
現代の C# では string.Format() の代わりに文字列補間($"{変数}")を使うことが多くなっています。ただし書式指定子(:P1 や :D6 など)は $"{値:書式}" の形式で文字列補間でも利用できます。
『PadLeft()』でゼロ埋めをする場合、数値.ToString("D6") のように数値の書式指定文字列を使う方法もあります。
文字列の分割と結合には『Split() / string.Join()』を参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。