LoginSignup
1
0

More than 1 year has passed since last update.

【C#】文字列を0や空白で埋める

Last updated at Posted at 2021-09-08

コード

文字列の場合
            string str = Console.ReadLine();
            //試しに1と入力

            Console.WriteLine(str.PadLeft(3, '0'));
            //001
            Console.WriteLine("{0,3:d}", str);
            //001

            //空白を挿入する場合
            Console.WriteLine(str.PadLeft(3, ' '));
            //  1
            //入力した文字数を含めた分の空白を入れる。この場合は空白2つ。

String.PadLeft()は左側から順番に指定した文字数になるまで埋めていく。
String.PadRight()はその逆。



数値の場合

            int N = int.Parse(Console.ReadLine());
            //1を入力

            Console.WriteLine(N.ToString("d3"));
            //001
            Console.WriteLine(string.Format("{0:d3}", N));
            //001

            //逆に0詰めをする場合
             Console.WriteLine(string.Format("{0,-3:d}a", N));
            //1  a
            //入力した文字数を含めた分の空白を入れる。この場合は空白2つ。


表示方法1つを取っても、様々な表し方があるのが面白いです。

ふと気になったのですが、
詰めるときのコードで表記している「d」は何の略語なんでしょうか…。

個人的には桁を意味するdigitの頭文字なのかな?と勝手に思っています。
何かを覚えるときは、意味を関連付けたほうが断然覚えやすいです。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0