toString() 메서드

toString()메서드에 문자열 배열을 전달하면 문자열 표현이 반환된다. 문자열 표현은 대괄호에 배열 요소로 구성된다.

class Main {
    public static void main(String[] args) {
        String[] strings = {"가", "나", "다","라"};
        String str = Arrays.toString(strings);

        System.out.println(str);
        
        // 출력결과 : [가, 나, 다, 라]
    }
}

StringBulilder.Append() 메서드

  • StringBuilder 타입의 객체를 생성하고 StringBuilder 클래스의 Append()메서드를 사용하여 문자열 요소를 하나씩 추가
  • 문자열 배열의 모든 요소가 StringBuilder 객체에 추가되면 toString()메서드를 사용하여 하나의 문자열로 만들 수 있다.
class Main {
    public static void main(String[] args) {
        String[] strings = {"가", "나", "다","라"};
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < strings.length; i++) {
            builder.append(strings[i]);
        }

        String str = builder.toString();

        System.out.println(str);
		// 실행결과 : 가나다라
    }
}

join() 메서드

String클래스의 join() 메서드를 사용하여 문자열 배열을 문자열로 반환할 수 있다.

join() 메서드는 두 개의 인수를 가지는데, 첫 번째 인수는 문자열의 요소, 두번째 인수는 문자열 배열을 말한다.

class Main {
    public static void main(String[] args) {
        String[] strings = {"가", "나", "다","라"};
        String str = String.join(", ", strings);

        System.out.println(str);
        //출력결롸 : 가, 나, 다, 라
    }
}

+ Recent posts