[Java] Intellij에서 한글과 숫자 고정 너비로 정렬하기

째욘·2024년 11월 10일
0

1. 문제 상황

아래와 같이 상품명, 수량, 금액을 정렬하여 출력해보자.

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로 표현한다.


즉, 전체 지정 자리수 중 한글 개수만큼 1번 차감하면 된다.


2. 해결 방법

먼저, 문자열 내에 있는 한글 문자의 수를 센다.

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));

출력 결과

0개의 댓글

관련 채용 정보