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
'study' 카테고리의 다른 글
액셀 VBA편집기 Module (메크로) 설정 및 사용 (행 자동 삽입) (1) | 2023.12.08 |
---|---|
DHCP, DNS 서버의 역할 (0) | 2023.12.06 |
서버OS(리눅스, 윈도우, 어플라이언스 서버, 범용서버) 정의 (1) | 2023.11.27 |
서버함체 형태, 구성컴포넌트(CPU,메모리,스토리지드라이브,NIC) (0) | 2023.11.24 |
DB 데이터타입 BLOB (2) | 2023.11.22 |