Caution
お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。
文字列.PadLeft() / PadRight()
文字列を指定した長さになるよう左側に文字を埋める『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} などのプレースホルダーを引数の値で置き換えた文字列を返します。 |
サンプルコード
using System;
// PadLeft() で右寄せ表示(数値の桁揃え)をします。
for (int i = 1; i <= 5; i++)
{
string 行 = i.ToString().PadLeft(3);
Console.WriteLine(行);
}
// PadLeft() でゼロ埋めをします。
string コード = "42".PadLeft(6, '0');
Console.WriteLine(コード); // 000042
// PadRight() で左寄せ表示をします。
string[] 商品 = { "りんご", "バナナ", "さくらんぼ" };
int[] 価格 = { 150, 80, 300 };
for (int i = 0; i < 商品.Length; i++)
{
Console.WriteLine(商品[i].PadRight(8) + 価格[i] + "円");
}
// string.Format() で書式を指定します。
string メッセージ = string.Format("{0}さんのスコアは{1}点です。", "田中", 95);
Console.WriteLine(メッセージ); // 田中さんのスコアは95点です。
// 数値の書式指定(小数点2桁など)もできます。
double 割引率 = 0.1567;
Console.WriteLine(string.Format("割引率: {0:P1}", 割引率)); // 割引率: 15.7%
概要
現代の C# では string.Format() の代わりに文字列補間($"{変数}")を使うことが多くなっています。ただし書式指定子(:P1 や :D6 など)は $"{値:書式}" の形式で文字列補間でも利用できます。
『PadLeft()』でゼロ埋めをする場合、数値.ToString("D6") のように数値の書式指定文字列を使う方法もあります。
文字列の分割と結合には『Split() / string.Join()』を参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。