복합 형식 출력
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 십진수
Console.Write("{0:D5}", 25); //00025
전자 또는 전자 과학
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/보간된
원시 문자열 리터럴:
https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/builtin-types/reference-types#string-literals