
{첨자, 맞춤: 서식 문자열}
using static System.Console;
namespace StringFormatBasic
{
class MainApp
{
static void Main(string[] args)
{
string fmt = "{0, -10}{1, 15}"; // 10칸의 공간 + 왼쪽 정렬, 15칸의 공간 + 오른쪽 정렬
WriteLine(fmt, "Publisher", "Title");
WriteLine(fmt, "Marble", "Iron Man");
WriteLine(fmt, "DC Comics", "Batman");
}
}
}
[실행 결과]
Publisher Title
Marble Iron Man
DC Comics Batman
| 서식 지정자 | 대상 서식 |
|---|---|
| D | 10진수 |
| X | 16진수 |
| N | 콤마(,)로 묶어 표현한 수 |
| F | 고정 소수점 |
| E | 지수 |
using static System.Console;
namespace StringFormatNumber
{
class MainApp
{
static void Main(string[] args)
{
WriteLine("10진수: {0:D}", 123);
WriteLine("10진수: {0:D} \n", 0xF);
WriteLine("10진수: {0:D5} \n", 123);
WriteLine("16진수: {0:X} \n", 0xFF1234);
WriteLine("숫자: {0:N}", 123);
WriteLine("숫자: {0:N1}", 123); // 소수점 첫째 자리까지 보존
WriteLine("숫자: {0:N0} \n", 123); // 소수점 이하 모두 제거
WriteLine("고정 소수점: {0:F}", 123.45);
WriteLine("고정 소수점: {0:F3} \n", 123.45);
WriteLine("공학: {0:E}", 123.45);
}
}
}
[실행 결과]
10진수: 123
10진수: 15
10진수: 00123
16진수: FF1234
숫자: 123.00
숫자: 123.0
숫자: 123
고정 소수점: 123.45
고정 소수점: 123.450
공학: 1.234500E+002
| 서식 지정자 | 대상 서식 |
|---|---|
| y | 연도 |
| M | 월 |
| d | 일 |
| h | 시 (1 ~ 12) |
| H | 시 (1 ~ 23) |
| m | 분 |
| s | 초 |
| tt | 오전/오후 |
| ddd | 요일 |
using System;
using System.Globalization;
namespace StringFormatDatetime
{
class MainApp
{
static void Main(string[] args)
{
DateTime dt = new DateTime(2023, 03, 27, 23, 15, 38);
Console.WriteLine(dt);
Console.WriteLine("\n{0:yyyy.MM.dd HH:mm:ss (ddd)}", dt);
CultureInfo ciKo = CultureInfo.GetCultureInfo("ko-KR");
CultureInfo ciEn = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(dt.ToString("\nyyyy.MM.dd tt hh:mm:ss (ddd)", ciKo));
Console.WriteLine(dt.ToString("yyyy.MM.dd tt hh:mm:ss (ddd)", ciEn));
}
}
}
[실행 결과]
2023-03-27 오후 11:15:38
2023.03.27 23:15:38 (월)
2023.03.27 오후 11:15:38 (월)
2023.03.27 PM 11:15:38 (Mon)
▪ 참고: Hello Fruit! - 문자열 보간: $