どうも、ちょげ(@chogetarou)です。
文字列(string)を空白埋めする方法を紹介します。
方法

文字列(string)を空白埋めする方法は、2つあります。
左側
ひとつは、左側を空白埋めする方法です。
まず、文字列からPadLeft()を呼び出します。
PadLeft()の引数に、文字数を指定します。
//text=対象の文字列, width=文字数
string result = text.PadLeft(width);
上記のPadLeft()は、文字列の文字数が引数の文字数よりも少ない場合に、文字列の左側を足りない文字数分空白埋めします。
PadLeft()は、文字列の左側を半角の空白で埋めます。
もし、全角の空白で埋めたい場合は、PadLeft()の第2引数に全角の空白の文字を指定します。
//全角の空白で埋める場合
//第2引数に全角の空白の文字を指定
string result = text.PadLeft(width, ' ');
使用例
using System;
public class Example
{
public static void Main()
{
string text = "Hello,World";
string result = text.PadLeft(15);
Console.WriteLine("|" + result + "|");
}
}
出力:
| Hello,World|
右側
もうひとつは、右側を空白埋めする方法です。
まず、文字列からPadRigth()を呼び出します。
PadRight()の引数に、文字数を指定します。
//text=対象の文字列, width=文字数
string result = text.PadRight(width);
上記のPadRight()は、文字列の文字数が引数の文字数よりも少ない場合に、文字列の右側を足りない文字数分空白埋めします。
PadRight()は、文字列の右側を半角の空白で埋めます。
もし、全角の空白で埋めたい場合は、PadRight()の第2引数に全角の空白の文字を指定します。
//全角の空白で埋める場合
//第2引数に全角の空白の文字を指定
string result = text.PadRight(width, ' ');
使用例
using System;
public class Example
{
public static void Main()
{
string text = "Hello,World";
string result = text.PadRight(15);
Console.WriteLine("|" + result + "|");
}
}
出力:
|Hello,World |
まとめ
文字列(string)を空白埋めする方法は、次の2つです。
- 左側を空白埋めする方法
string result = text.PadLeft(width);
- 右側を空白埋めする方法
string result = text.PadRight(width, ' ');
コメント