Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
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
Archives
Today
Total
관리 메뉴

KSI일기장

Java 배열을 문자로 변환 , 문자를 배열로 변환, 다른 자료형을 문자로 변환(String.join() , toCharArray() , String.valueOf() , Arrays.toString() ) 본문

study

Java 배열을 문자로 변환 , 문자를 배열로 변환, 다른 자료형을 문자로 변환(String.join() , toCharArray() , String.valueOf() , Arrays.toString() )

MyDiaryYo 2023. 12. 5. 13:53

 

 

String.join("각요소 사이 삽입할 문자열", "결합할 문자열 요소들")

배열 문자열로 변환

ex)

 public static void main(String[] args) {
        String[] words = {"123", "456", "7"};

        String  coalescence = String.join("", words);

        System.out.println(coalescence);
 }

 

결과: "1234567"

 

 

 

Arrays.toString("String으로 변경할 배열 변수명")

: 배열 문자열로 변환

ex) to String을 이용해 String으로 변환 후 for문을 이용한 출력

public static void main(String[] args) {
	int[] num = {1,2,3,4,5};
        String numSt = Arrays.toString(num);
        String aaa = "";
        for (int j=0; j< numSt.length(); j++) {
            aaa += numSt.charAt(j);
        }
        System.out.println(aaa);
}

 

ex) to String을 이용해 String으로 변환하면서 String에 담아서 출력

 public static void main(String[] args) {
        
            int[] num = {1,2,3,4,5};
            String numSt = new String(Arrays.toString(num));
            
            System.out.println(numSt);
    }

결과: [1,2,3,4,5]

        --> 결과값에 []가 붙는 이유는 배열을 문자열로 변환할때 대괄호( [] )로 감싸고 요소들을 쉼표로 구분하기 때문이다.

ex1과 ex2는 똑같이 Arrays.to String으로 배열을 문자열로 변환하지만 

 

 

 

 new String("String으로 변경할 배열 변수명")

: 배열 문자열로 변환

ex1)

 public static void main(String[] args) {

        String[] answerArr = {"가", "다라", "마바사", "아자차"};
        String answer = new String(Arrays.toString(answerArr));

        System.out.println(answer);
    }

결과: [가, 다라, 마바사, 아자차]

 

ex2)

 public static void main(String[] args) {

        char[] answerArr = {'가', '나', '다', '라'};
        String answer = new String(answerArr);

        System.out.println(answer);
 }

결과: 가나다라

 

 

 

String.valueOf("String으로 변경할 변수명")

: 다른 자료형 문자열로 변환

String.valueOf를 이용해 문자열로 변환할 수 있는 자료형

 = boolean, char, int, long, float, double, char[]

ex)

public static void main(String[] args) {
    int age = 20;
    String stringAge = String.valueOf(age);

    System.out.println(stringAge);
}

결과: "20"

 

 

 

char[] 변수명 = 변환할 문자열.toCharArray()

: 문자열 배열로 변환

ex)

 public static void main(String[] args) {
      
        String word = "1234567";

        char[] coalescense2 = word.toCharArray();

        for (int i=0; i<coalescense2.length; i++){
            System.out.print(coalescense2[i]);
        }
    }

결과: 1234567