やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

C#チュートリアル(文字列補完)

 $"{変数}"で文字列化できる記法。

成果物

情報源

プロジェクト作成

dotnet new console -o Tutorial_StringComplement
cd Tutorial_StringComplement

コード

サクッと

using System;

namespace Tutorial_StringComplement.Lesson0
{
    class Main
    {
        public void Run()
        {
            var name = "<name>";
            Console.WriteLine($"Hello, {name}. It's a pleasure to meet you!");
        }
    }
}
Hello, <name>. It's a pleasure to meet you!

 これまでは以下のように文字列結合するなりして書かねばならなかった。その場合、もし文字列型でなければvar.ToString()のようにせねばならず面倒。

Console.WriteLine("Hello, " + name + ". It's ...");

さまざまな型で使える

 文字列の他にも、数値や日付など任意の型で使える。

var item = new Vegetable("eggplant");
var date = DateTime.Now;
var price = 1.99m;
var unit = Unit.item;
Console.WriteLine($"On {date}, the price of {item} was {price} per {unit}.");
On 2019/10/24 10:44:24, the price of eggplant was 1.99 per item.

書式設定

Console.WriteLine($"On {date:d}, the price of {item} was {price:C2} per {unit}.");
On 2019/10/24, the price of eggplant was ¥1.99 per item.

幅設定

var titles = new Dictionary<string, string>()
{
    ["Doyle, Arthur Conan"] = "Hound of the Baskervilles, The",
    ["London, Jack"] = "Call of the Wild, The",
    ["Shakespeare, William"] = "Tempest, The"
};
Console.WriteLine("Author and Title List");
Console.WriteLine();
Console.WriteLine($"|{"Author",-25}|{"Title",30}|");
foreach (var title in titles)
    Console.WriteLine($"|{title.Key,-25}|{title.Value,30}|");

 実行すると以下。

Author and Title List

|Author                   |                         Title|
|Doyle, Arthur Conan      |Hound of the Baskervilles, The|
|London, Jack             |         Call of the Wild, The|
|Shakespeare, William     |                  Tempest, The|

 右寄せにするなら以下。

Console.WriteLine($"|{"Author",25}|{"Title",30}|");
foreach (var title in titles)
   Console.WriteLine($"|{title.Key,25}|{title.Value,30}|");
|                   Author|                         Title|
|      Doyle, Arthur Conan|Hound of the Baskervilles, The|
|             London, Jack|         Call of the Wild, The|
|     Shakespeare, William|                  Tempest, The|

 日時や数値に対してやると以下。

Console.WriteLine($"[{DateTime.Now,-20:d}] Hour [{DateTime.Now,-10:HH}] [{1063.342,15:N2}] feet");
[2019/10/24          ] Hour [11        ] [       1,063.34] feet
  • $"{変数}": $"{DateTime.Now}"
  • $"{変数, 幅:書式}": $"{DateTime.Now, -10:hh}"

所感

 文字列補完は、C#新機能のチュートリアルなどで少し触れたやつ。C言語でいうsprintf関数の豪華版みたいなものなんだろう。便利。

おまけ

 ""String.Emptyって違うの? と疑問に思ったのでググった。

 よくわからん。以下のようなことらしいと理解したが。

 まあいいや。細かいことは追々やろう。

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux