複合フォーマット出力
string name = "Fred";
String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now);
同じ引数指定子を指定することにより、複数の書式項目がオブジェクト リスト内の同じ要素を参照できます。たとえば、「0x{0:X} {0:E} {0:N}」などの複合フォーマット文字列を指定すると、次のように、同じ値を 16 進数、指数表記、および数値でフォーマットできます。 :
string multiple = String.Format("0x{0:X} {0:E} {0:N}",
Int64.MaxValue);
Console.WriteLine(multiple);
// The example displays the following output:
// 0x7FFFFFFFFFFFFFFF 9.223372E+018 9,223,372,036,854,775,807.00
D または d 10 進数
Console.Write("{0:D5}", 25); //00025
Eまたはe科学
Console.Write("{0:E}", 250000); //2.500000E+005
F または f フロート
Console.Write("{0:F2}", 25); //25.00
Console.Write("{0:F0}", 25); //25
N または n 個の数字
Console.Write("{0:N}", 2500000); //2,500,000.00
X または x 16 進数
Console.Write("{0:X}", 250);
時間を表示するために使用できます。たとえば、次のようになります。
int hour = 7;
int minutes = 59;
int seconds = 3;
string timeString = string.Format("{0:00}:{1:00}:{2:00}", hour, minutes, seconds);
Debug.Log(timeString); // 输出:07:59:03
補間された文字列 $
$ 特殊文字は、文字列リテラルを補間文字列として識別します。補間された文字列は、補間された式を含む可能性がある文字列リテラルです。補間された文字列を解析して結果の文字列にする場合、補間された式を含むアイテムは、式の結果の文字列表現に置き換えられます。
string name = "Mark";
var date = DateTime.Now;
// 复合格式:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// 字符串内插:
Console.WriteLine($"Hello, {
name}! Today is {
date.DayOfWeek}, it's {
date:HH:mm} now.");
// 两者输出完全相同,如下:
// Hello, Mark! Today is Wednesday, it's 19:40 now.
オプションのフォーマット
{
<interpolationExpression>[,<alignment>][:<formatString>]}
好き
Console.WriteLine($"|{
"Left",-7}|{
"Right",7}|");
const int FieldWidthRightAligned = 20;
Console.WriteLine($"{
Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{
Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Expected output is:
// |Left | Right|
// 3.14159265358979 - default formatting of the pi number
// 3.142 - display only three decimal digits of the pi number
生の文字列 (3 つの引用符) と式 (例: {Math.Sqrt(X * X + Y * Y)} ) もサポートされています.
文字列リテラルには、エスケープ シーケンスなしで任意のテキストを含めることができます. 文字列リテラルには、スペースと改行、埋め込み引用符、およびその他の特殊文字を含めることができます。
int X = 2;
int Y = 3;
var pointMessage = $"""The point "{X}, {Y}" is {
Math.Sqrt(X * X + Y * Y)} from the origin""";
Console.WriteLine(pointMessage);
// output: The point "2, 3" is 3.605551275463989 from the origin.
団結
debug.log など、文字列型パラメーターを使用するすべての場所を使用できます。
string path = Application.persistentDataPath + "DataSave.json";
Debug.Log($"File not exist : {
path}");
参考
複合:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting
補間:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference /tokens/interpolated
raw 文字列リテラル:
https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/builtin-types/reference-types#string-literals