개발입문/JAVA

Java String Formatting

haloaround 2017. 9. 10. 12:36


Formatter, REGEX 는 아직 어렵다.

예를 들어, 테이블 컬럼에 15자가 들어가고,

그 안에 String 값이 1~15자부터 자유롭게 들어갈 수 있을 때, 패딩을 어떻게 유동적으로 주어야하는가.


Java Output Formatting

> https://www.hackerrank.com/challenges/java-output-formatting





Q. 이걸 도대체 어떻게 검색하죠? 

내가 검색한 쿼리: String space format 

영어 표현: pad a given string

찾았다!


String Formatter

> https://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java


Since 1.5, String.format() can be used to left/right pad a given string.

public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  
}

public static String padLeft(String s, int n) {
    return String.format("%1$" + n + "s", s);  
}

...

public static void main(String args[]) throws Exception {
 System.out.println(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 20) + "*");
}
/*
  output :
     Howto               *
                    Howto*
*/




하지만 여기서 멈출 수 없지.

이제 String.format 을 Doc.에서 찾아본다.

public static String format(String format,
                            Object... args)
Returns a formatted string using the specified format string and arguments.


포맷에 맞추어 Formatted String 값을 전달한단다.

format 에 대한 표현은 어떻게 구현하는 거죠?




Format string. 그래서 포맷은 무엇이냐? 

format string 을 클릭하면, Formatter 클래스로 이동ㅇ한다.


public final class Formatter extends Object implements Closeable, Flushable


The format string is a String which may contain fixed text and one or more embedded format specifiers

Format string 은 고정된 텍스트와 내장된 포맷들을 포함합니다.

그리고 일반적인 Syntax는 다음과 같다.

 %[argument_index$][flags][width][.precision]conversion

Conversions: c(character), d(decimal), f(floating point), %(literal), n(line separator)

Flags: - (left-justified), #(conversion-dependant alternative form), 

Width: minimum number of characters to be written

Precision: maximum number of characters to be written, for floating-point conversions the number of digits after the radix point

Argument Index: decimal integer indicating the position of argument in the argument list




자주 쓰는 포맷 예시

"%1$-15s", "%-15s"

1$               Argument index: 첫번째의

-                 Flag: left-justified 왼쪽정렬된

15               Width: 15개 너비의

s                 Conversion: String 값


"%.3f"
.3            Precision (소수점 셋째자리)
f              Conversion 소수



포맷 예시는 보는대로 추가해나가야겠다.

포맷지시자를 보고 포맷을 파악하는데 의의를 두고,

그리고 자주 쓰는 표현들은 외워버려야지 +_+.