前ゼロ埋めするには「PadLeft」を使用します。
(C#)PadLeft で前ゼロ埋めをする方法
ゼロ埋め結果 = 文字列.PadLeft(桁数, '0');
使用例
string before = "123";
// 10桁で前ゼロ埋め
string after = before.PadLeft(10, '0');
// 結果 = "0000000123"
Console.WriteLine(after);
// 結果 = "123"(元の文字列はそのまま)
Console.WriteLine(before);
(VB.NET)PadLeft で前ゼロ埋めをする方法
ゼロ埋め結果 = 文字列.PadLeft(桁数, "0")
使用例
dim before As string = "123"
' 10桁で前ゼロ埋め
dim after As string = before.PadLeft(10, "0")
' 結果 = "0000000123"
Console.WriteLine(after)
' 結果 = "123"(元の文字列はそのまま)
Console.WriteLine(before)
サンプルコードのダウンロード
サンプルコードの実行には Microsoft Visual Studio 2015 以上のバージョンが必要です。 2015以外のバージョンではプロジェクトを開いた際にファイルの変換が必要な場合があります。その場合は変換後に実行してください。検証環境
- Microsoft Visual Studio Professional 2017 Version 15.7.3
- Microsoft .NET Framework Version 4.7.03190
- Microsoft Windows 10 Pro Version 1809 OS Build 17763.404