본문 바로가기

C# 공부/C# 기본 문법

문자열 서식 맞추기 (Format(), 문자열 보간)

1. Format() 메소드

기본적으로 Console.WriteLine("제목 :{0}", "이것이 C#이다"); 메소드 내부에서 String.Format() 메소드가 동작하고있다.

 

- 구조

{첨자, 맞춤 : 서식 문자열}

첨자 : 서식 항목의 첨자

맞춤 : 왼쪽(-)/오른쪽 맞춤

서식문자열 : 변환 서식 지정 문자열

 

a. 맞춤기능 : 프로그램이 여러개의 항목을 가지런히 출력할때 필요하다.

string result = string.Format{"{0}DEF","ABC"};

// result = "ABCDEF"

 

string result = string.Format{"{0,-10}DEF","ABC"};

// result = "ABC       DEF"

 

string result = string.Format{"{0,10}DEF","ABC"};

// result = "       ABCDEF"

 

* 예시코드 

string fmt = "{0,20}{1,-15},{2,30}";

 

WriteLine(fmt, "Publisher", "Author", "Title");

WriteLine(fmt, "Marvel", "Stan Lee", "Iron Man");

WriteLine(fmt, "Hanbit", "Sanghyun Park", "C# 7.0 Programming");

WriteLine(fmt, "Prentice Hall", "K&R", "The C Programming Language");

 

b. 숫자 서식화 : 날짜 및 시간, 콤마로 묶어 표현한 금액, 고정소수점, 지수 형식표현시 쓰인다.

서식지정자+숫자에서 숫자는 자릿수로 쓰임.

'D' : 10진수

WriteLine("{0:D}",255);  //255

WriteLine("{0:D}",0xFF); //255

'N' : 콤마로 묶어 표현한 수

WriteLine("{0:N}",123456789); //123,456,789.00

 

ex)

WriteLine("10진수: {0:D}", 123); //00123

 

날짜 및 시간 서식화

DateTime 클래스가 필요하다.

DateTime dt = new DateTime(2018,11,3,23,18,22);// 2018년 11월 3일 23시 18분 22초

WriteLine("{0}",dt); //2018-11-03 오후 11:18:22가 출력됨.

y : 연도, M : 월, d : 일, h : 시(1~12), H : 시(1~23), m : 분, s : 초, tt : 오전/오후, ddd : 요일

 

ex)

WriteLine("12시간형식: {0:yyyy-MM-dd tt hh:mm:ss (ddd)}", dt); // 12시간 형식: 2018-11-03 오후 11:18:22 (토)

 

2. 문자열 보간(Interpolation)

C#6.0 이후 사용가능하며, 비거나 누락된부분을 채운다. String.Format()과 다른점은 문자열 틀 앞에 $기호를 붙인다는 것, 서식항목에 첨자대신 식이 들어간다는것. 식에는 변수나 객체이름, 상수, 조건에따라 다른값을 출력하는 코드가 들어갈수있다.

 

-형식

$ "텍스트{<보간식>[,길이] [:서식]}텍스트{....}..."

string.Format() 문자열보간
WriteLine("{0},{1}",123,"최강한화"); WriteLine($"{123},{"최강한화"}");
WriteLine("{0,-10,D5},123); WriteLine($"{123,-10:D5}");
int n = 123;
string s = "최강한화";

WriteLine("{0},{1}",n,s);
int n=123;
string s="최강한화";

WriteLine($"{n},{s}");
int n=123;

WriteLine("{0}",n>100?"큼","작음",s);
int n=123;

WriteLine($"{(n>100?"큼":"작음")}");