Developer Factory

String format 사용법 본문

Developer/JAVA restart

String format 사용법

Jeremy.Park 2019. 8. 2. 21:43

String format 형식

String클래스의 format 메소드는 지정된 위치에 값을 대입해서 문자열을 만들어 내는 용도로 사용하며 형식은 아래와 같이 정의되어 있습니다.

[중요!! String format문 형식]

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

%와 conversion은 필수 항목이지만 대괄호로 되어있는 [argument_index$][flags][width] 부분은 생략 가능합니다.

즉, %conversion 형식으로 사용할 수 있고 나머지 부분은 옵션이라는 뜻입니다.

conversoin위치에는 출력되는 데이터의 타입을 입력하는데 s(문자열), d(정수), x(16진수), o(8진수), f(실수)가 들아갈 수 있습니다.

String format문 형식에서 언급했듯이 %는 필수이므로 코드는 %s, %d, %x, %o, %f로 사용됩니다.

대괄호 부분은 잠시 후에 설명되므로 우선 String format문의 형식만 잘 기억해두시기 바랍니다.

문자열 format

먼저 conversoin위치에 문자열을 나타내는 s를 넣어서 샘플을 만들어 보겠습니다.

1

2

3

4

5

6

System.out.println("[example 1]");

// 문자열이 출력되는 위치를 확인하기 위해 1~0의 숫자를 반복 출력합니다.

System.out.println("12345678901234567890");

 

// %s를 이용한 문자열 출력

System.out.println(String.format("%s, %s", "KOREA", "JAPAN"));

[example 1] 12345678901234567890 KOREA, JAPAN

출력 결과는 KOREA, JAPAN 두 개의 문자열이 %s 위치에 대입되고 %s를 제외한 쉼표나 공백은 그대로 출력 됩니다. 

실제 프로그래밍을 할때는 "KOREA" "JAPAN"과 같은 문자열 상수를 사용하는 경우는 거의 없고 문자열 변수를 대입해서 사용합니다.

width 옵션

다음은 String format 형식 중 conversion앞에 위치하는 [width]를 사용한 샘플입니다. %와 s와 사이에 원하는 길이를 지정하면 되는데 10으로 지정해서 출력해 보겠습니다.

1

2

3

4

5

6

7

8

9

10

System.out.println("[example 2]");

// 문자열이 출력되는 자리를 확인하기 위해 숫자를 출력합니다..

System.out.println("12345678901234567890");

 

// 길이를 10으로 지정 (width 옵션)

System.out.println(String.format("%10s%10s", "KOREA", "JAPAN"));

 

// 길이를 10으로 지정 (width +  argument_index 옵션)

System.out.println(String.format("%2$10s%1$10s", "KOREA", "JAPAN"));

[example 2] 12345678901234567890 KOREA JAPAN JAPAN KOREA

출력결과와 같이 KOREA와 JAPAN이 출력되고 width를 10자리로 지정헸기 때문에 문자열 왼쪽에 5개의 공백이 채워지게 됩니다.

argument_index 옵션

위 샘플을 보면 JAPAN과 KOREA위치가 서로 바뀌어서 출력됐는데 String format 형식 중 % 다음에 위치하는 [argument_index]를 추가 했기 때문입니다. 소스 코드를 보면 2$와 1$를 각 각 추가했는데 2$는 두번 째 문자열인 "JAPAN"을 의미하고 1$는 첫 번째 "KOREA"를 의미하기 때문에 출력 순서가 바뀐 것입니다.

flags를 옵션

다음 샘플은 마이너스 기호인 - flags를 사용한 샘플입니다. String format 형식을 다시 확인해보시면 [flags]는 [argument_index]와 [width]사이에 위치합니다.

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

- flag를 사용하면 출력되는 문자열이 왼쪽으로 정렬 됩니다.

1

2

3

System.out.println("[example 3]");

System.out.println("12345678901234567890");

System.out.println(String.format("%-10s%-10s", "KOREA", "JAPAN"));

[example 3] 12345678901234567890 KOREA JAPAN

KOREA와 JAPAN 문자열이 각 10자리를 차지하면서 - flag로 인해 왼쪽으로 정렬되었습니다. - flag를 빼면 이전 예제와 같이 오른쪽으로 정렬됩니다.

정수 format

정수는 %뒤에 d를 붙여서 사용합니다.

1

2

3

System.out.println("[example 4]");

System.out.println(String.format("12345678901234567890"));

System.out.println(String.format("%d, %d", 12345, 67890));

[example 4] 12345678901234567890 12345, 67890


문자열과 같이 길이를 지정하거나 위치를 바꿀 수 있습니다.

1

2

3

4

System.out.println("[example 5]");

System.out.println("12345678901234567890");

System.out.println(String.format("%10d%10d", 12345, 67890));

System.out.println(String.format("%2$10d%1$10d", 12345, 67890));

[example 5] 12345678901234567890 12345 67890 67890 12345

첫번째 라인은 10자리로 지정해서 남는 왼쪽 부분은 공백으로 채운 것이고 두 번째 라인은 문자열 샘플에서 사용했던 [argument_index]를 이용 두 번째 파라메터은 67890이 먼저 출력 되도록 지정한 샘플 코드입니다.


문자열에 사용했듯이 - flag를 사용해서 왼쪽 정렬도 사용 할 수 있습니다.

1

2

3

System.out.println("[example 6]");

System.out.println("12345678901234567890");

System.out.println(String.format("%-10d%-10d", 12345, 67890));

[example 6] 12345678901234567890 12345 67890


이번엔 0 flag를 사용해서 공백 부분은 0으로 채우겠습니다.

1

2

3

System.out.println("[example 7]");

System.out.println("12345678901234567890");

System.out.println(String.format("%010d%010d", 12345, 67890));

[example 7] 12345678901234567890 00000123450000067890

문자열 샘플에서 사용했던 - flag는 모든 타입에 사용할 수 있지만 0 flag는 정수나 실수를 대입할때만 사용가능하며 문자열 등에는 사용할 수 없습니다.

타입별도 사용 가능한 flag는 아래 이미지를 참고해주세요. y로 표시되어 있는 경우에만 사용 가능합니다.


정수, 실수에 사용 가능한 몇가지 flag를 더 사용해 보겠습니다. + flag를 사용한 샘플입니다.

1

2

3

System.out.println("[example 8]");

System.out.println("12345678901234567890");

System.out.println(String.format("%+10d%+10d", 100, -200));

[example 8] 12345678901234567890 +100 -200

+ flag를 사용하면 부호를 표시합니다.


부호를 표시하면서 남는 자리수는 0으로 채우는 샘플입니다.

1

2

3

System.out.println("[example 9]");

System.out.println("12345678901234567890");

System.out.println(String.format("%+010d%+010d", 100, -200));

[example 9] 12345678901234567890 +000000100-000000200


( flag를 사용한 샘플입니다.

1

2

3

System.out.println("[example 10]");

System.out.println("12345678901234567890");

System.out.println(String.format("%(10d%(10d", 100, -200));

[example 10] 12345678901234567890 100 (200)

( 를 사용하면 음수인 경우만 괄호가 사용됩니다.


, flag를 사용한 샘플입니다.

1

2

3

System.out.println("[example 11]");

System.out.println("12345678901234567890");

System.out.println(String.format("%,10d%,10d", 10000, -20000));

[example 11] 12345678901234567890 10,000 -20,000

,를 사용하면 해당 국가에서 사용되는 기호로 숫자를 그룹지어 줍니다. 대부분 콤마가 사용될 것 같네요.


16진수 format

x를 사용하면 16진수를 출력합니다. 아래 샘플에서는 10진수 2047이 16진수로 변환되서 출력 됩니다.

1

2

3

System.out.println("[example 12]");

System.out.println("12345678901234567890");

System.out.println(String.format("%10x%10x", 2047, 2047));

[example 12] 12345678901234567890 7ff 7ff


X를 대문자로 사용하면 16진수도 대문자로 출력됩니다.

1

2

3

System.out.println("[example 13]");

System.out.println("12345678901234567890");

System.out.println(String.format("%10X%10X", 2047, 2047));

[example 13] 12345678901234567890 7FF 7FF


8진수 format

o를 사용하면 8진수를 출력합니다. 아래 샘플에서는 10진수 2047이 8진수로 변환되서 출력 됩니다.

1

2

3

System.out.println("[example 14]");

System.out.println("12345678901234567890");

System.out.println(String.format("%10o%10o", 2047, 2047));

[example 14] 12345678901234567890 3777 3777


실수 format

실수는 f를 사용합니다. 사용법은 정수와 거의 같고 .을 사용하면 정밀도를 지정 할 수 있습니다. 아래 샘플에서는 정밀도를 소숫점 두 자리까지 지정 했는데 .99가 아니라 .00으로 출력되는 이유는 반올림 되었기 때문입니다.

1

2

3

System.out.println("[example 15]");

System.out.println("12345678901234567890");

System.out.println(String.format("%10.2f%10.2f", 100000.999f, 200000.999f));

[example 15] 12345678901234567890 100001.00 200001.00

전체 소스와 참고 URL

글의 대부분의 내용은 아래 URL을 참고했습니다. 더 자세한 설명이나 부족한 부분은 링크를 참고해 주세요~

https://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax

그리고 설명에 사용된 샘플 코드 입니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

public class Test {

    public static void main(String[] args){

        System.out.println("[example 1]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%s, %s", "KOREA", "JAPAN"));

        System.out.print("\n");

         

        System.out.println("[example 2]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%10s%10s", "KOREA", "JAPAN"));

        System.out.println(String.format("%2$10s%1$10s", "KOREA", "JAPAN"));

        System.out.print("\n");

 

        System.out.println("[example 3]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%-10s%-10s", "KOREA", "JAPAN"));

        System.out.print("\n");

 

        System.out.println("[example 4]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%d, %d", 12345, 67890));

        System.out.print("\n");

 

        System.out.println("[example 5]");

        System.out.println("12345678901234567890");

        System.out.println("%10d%10d", 12345, 67890));

        System.out.println(String.format("%2$10d%1$10d", 12345, 67890));

        System.out.print("\n");

         

        System.out.println("[example 6]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%-10d%-10d", 12345, 67890));

        System.out.print("\n");

         

        System.out.println("[example 7]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%010d%010d", 12345, 67890));

        System.out.print("\n");

 

        System.out.println("[example 8]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%+10d%+10d", 100, -200));

        System.out.print("\n");

 

        System.out.println("[example 9]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%+010d%+010d", 100, -200));

        System.out.print("\n");

         

        System.out.println("[example 10]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%(10d%(10d", 100, -200));

        System.out.print("\n");

 

        System.out.println("[example 11]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%,10d%,10d", 10000, -20000));

        System.out.print("\n");

 

        System.out.println("[example 12]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%10x%10x", 2047, 2047));

        System.out.print("\n");

 

        System.out.println("[example 13]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%10X%10X", 2047, 2047));

        System.out.print("\n");

 

        System.out.println("[example 14]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%10o%10o", 2047, 2047));

        System.out.print("\n");

 

        System.out.println("[example 15]");

        System.out.println("12345678901234567890");

        System.out.println(String.format("%10.2f%10.2f", 100000.999f, 200000.999f));

        System.out.print("\n");

    }

}


 

원문: http://blog.devez.net/100

'Developer > JAVA restart' 카테고리의 다른 글

자바 키워드  (0) 2019.08.02