Java
String.format 이용한 문자열 형식 설정
심나라
2022. 8. 1. 14:33
728x90
String.format 메서드는 문자열의 형식을 설정하는 메서드이고 7가지의 형식을 제공합니다.
- %d (10진수 형식)
- %s (문자열 형식)
- %f (실수형 형식)
- Locale 설정
- %t (날짜시간 형식)
- %c (유니코드 문자 형식)
- %o, %x(8진수, 16진수 형식)
%d (Integer Formatting)
10진수 포맷을 설정할 때 사용합니다.
int i = 12;
System.out.println(String.format("Integer Formating :%d", i));
System.out.println(String.format("Integer Formating :%5d", i));
System.out.println(String.format("Integer Formating :%-5d", i));
System.out.println(String.format("Integer Formating :%05d", i));
/*
출력결과
Integer Formating :12
Integer Formating : 12
Integer Formating :12
Integer Formating :00012
*/
- %d : 정수를 그대로 출력함.
- %5d : 기본적으로 오늘쪽 정렬이고 숫자가 있는경우, 나머지 길이에 대해서 공백으로 채움
- %-5d : '-' 가 있는 경우 왼쪽 정렬이고, 나머지 길이에 대해서 공백으로 채움
- %05d : i의 값이 5(숫자)보다 작을경우 0으로 채움
%s (String Formatting)
문자열의 포맷을 설정할 때 사용합니다.
String str = "TXT";
System.out.println(String.format("String Formation :%s", str));
System.out.println(String.format("String Formation :%5s", str));
System.out.println(String.format("String Formation :%-5s", str));
System.out.println(String.format("String Formation :%.2s", str));
System.out.println(String.format("String Formation :%-5.2s", str));
System.out.println(String.format("String Formation :%5.2s", str));
/*
출력결과
String Formation :TXT
String Formation : TXT
String Formation :TXT
String Formation :TX
String Formation :TX
String Formation : TX
*/
- %s : 문자열을 그대로 출력
- %5s : 기본적으로 오른쪽 정렬이고, 문자열의 길이가 5(숫자)보다 작을경우 공백으로 채움
- %-5s : '-' 가 있는 경우 왼쪽 정렬이고, 문자열의 길이가 5(숫자)보다 작을 경우 공백으로 채움
- %.2s : '.(점)' 이 있는경우, 최대 2(숫자) 길이 만큼만 출력
- %-5.2s : 왼쪽 정렬이고, 최대 '숫자' 길이 만큼만 출력하고, 5(숫자)보다 작을 경우 공백으로 채움
- %5.2s : 오른쪽 정렬이고, 최대 '숫자' 길이 만큼만 출력하고, 5(숫자)보다 작을 경우 공백으로 채움
%t (DateTime Formatting)
날짜 포맷을 설정할 때 사용합니다.
Date now = new Date();
System.out.println(now);
System.out.println(String.format("DateTime Formation : %tF", now));
System.out.println(String.format("DateTime Formation : %tT, %tR", now, now));
System.out.println(String.format("DateTime Formation : %ty, %tY", now, now));
System.out.println(String.format("DateTime Formation : %tm", now));
System.out.println(String.format("DateTime Formation : %td, %te", now, now));
System.out.println(String.format("DateTime Formation : %tH", now));
System.out.println(String.format("DateTime Formation : %tM", now));
System.out.println(String.format("DateTime Formation : %tS", now));
/*
출력결과
Mon Aug 01 14:06:39 KST 2022
DateTime Formation : 2022-08-01
DateTime Formation : 14:06:39, 14:06
DateTime Formation : 22, 2022
DateTime Formation : 08
DateTime Formation : 01, 1
DateTime Formation : 14
DateTime Formation : 06
DateTime Formation : 39
*/
728x90