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

文字列(string)の右側を空白埋めするには、PadRight()を使います。
まず、文字列から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 |
コメント