아래와 같이 상품명, 수량, 금액을 정렬하여 출력해보자.
System.out.printf("%-12s%-8s%-10s%n", "상품명", "수량", "금액");
System.out.printf("%-12s%-8s%-10s%n", "콜라", "3", "3,000");
System.out.printf("%-12s%-8s%-10s%n", "누네띠네", "5", "10,000");
참고로, 출력 메서드 printf() 서식은 다음과 같다.
System.out.printf("[%s]%n", word);
System.out.printf("[%30s]%n", word); // 30칸 중 오른쪽 정렬
System.out.printf("[%-30s]%n", word); // 30칸 중 왼쪽정렬
출력 결과
상품명 수량 금액
콜라 3 3,000
누네띠네 5 10,000
의도한 일정 너비로(12/8/10) 정렬되지 않는다.
한글이 영문이나 숫자보다 넓은 폭을 차지하기 때문에 발생하는 문제다.
UTF-8 기준, 한글은 3byte, 영문 or 숫자는 2byte로 표현한다.
하지만 Intellij UTF-8 기준, 한글은 2byte, 영문 or 숫자는 1byte로 표현한다.
먼저, 문자열 내에 있는 한글 문자의 수를 센다.
public int getKoreanCount(String korean) {
return (int) korean.chars()
.filter(ch -> ch >= '가' && ch <= '힣')
.count();
}
보정된 폭에 맞춰 문자열을 출력할 수 있도록 한다.
public String convert(String word, int size) {
int adjustedSize = size - getKoreanCount(word); // 한글의 개수를 한 번 차감해 조정
String formatter = String.format("%%%ds", adjustedSize * -1); // 오른쪽 정렬일 경우, 그냥 adjustedSize
return String.format(formatter, word);
}
위 convert 함수를 사용해서 출력해보자.
System.out.printf("%s%s%s%n", convert("상품명", 12), convert("수량", 8), convert("금액", 10));
System.out.printf("%s%s%s%n", convert("콜라", 12), convert("3", 8), convert("3,000", 10));
System.out.printf("%s%s%s%n", convert("누네띠네", 12), convert("5", 8), convert("10,000", 10));
출력 결과