Java - charAt()

Esther·2022년 11월 19일
0

JAVA공부

목록 보기
3/7

scanner 사용시
char타입으로 입력받을 수 없고
String으로 입력받는데,
char형태로 사용해야할 때 주로 charAt()으로
String값을 char타입으로 변환해준다.

String str = "hello";
char ch = str.charAt(0);

charAt(i) 에서 i는 index번호이다.

String str = "hello";

char ch0 =str.charAt(0);
char ch1 =str.charAt(1);
char ch2 =str.charAt(2);
char ch3 =str.charAt(3);
char ch4 =str.charAt(4);

System.out.println(ch0);
System.out.println(ch1);
System.out.println(ch2);
System.out.println(ch3);
System.out.println(ch4);

출력결과:
h
e
l
l
o

<반복문활용>

String str = "hello world";

for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
System.out.println(ch);
}

출력결과 :
h
e
l
l
o

w
o
r
l
d

0개의 댓글