개발일지/수업내용
210809(월)_DAY 14 (charAt, toCharArray) // 추가 예정
jungwonyu
2021. 8. 10. 00:07
728x90
charAt
- Returns the char value at the specified index.
지정된 인덱스의 문자값을 반환
- Returns: The first char value is at index 0.
인덱스는 0부터 시작
- Throws: Index argument is negative or not less than the length of this string.
인덱스가 음수이거나 문자열의 길이보다 작을 때는 예외
eg/
public class P_Charat {
public static void main(String[] args) {
String str = "abcd";
System.out.println(str.charAt(0));
}
}
▶Console |
a |
toCharArray
- Converts this string to a new character array.
새로운 문자 배열로 변환
eg/
public class P_toCharArray {
public static void main(String[] args) {
String str = "Welcome My Tistory";
char[] res = str.toCharArray();
System.out.println(Arrays.toString(res));
}
}
▶Console |
[W, e, l, c, o, m, e, , M, y, , T, i, s, t, o, r, y] |
exam/ 사번 "111ABC" "222DEF"에서 첫 글자만 숫자로 변환해서 합을 구해보자.
public class ArrayTest01 {
public static void main(String[] args) {
String res = args[0];
String res01 = args[1];
char ch = args[0].charAt(0);
char ch02 = args[1].charAt(0);
int hap = Character.digit(ch, 10) + Character.digit(ch02, 10);
System.out.println(hap);
}
}
▶Console |
3 |
Character.digit 부분이 있어야 문자 ch를 숫자 값으로 반환한다!
digit(char ch, int radix) ← 이와 같이 작성 radix는 기수를 뜻하며 위의 코드와 같이 10이라고 쓰면 10진법임
exam/ 역순으로 문자열을 리턴해보자.
public class ArrayTest02 {
public static String ConString(String str) {
// 1. char[]배열로 리턴 받는다
char res[] = str.toCharArray();
char[] cv_str = new char[res.length];
// 2. 역순으로 for를 이용해서 char[]로 담아 String 생성자로 객체 생성 후 리턴
for (int i = res.length - 1; i >= 0; i--) {
cv_str[res.length - i - 1] = res[i]; // -1을 붙이는 이유: length와 index는 1차이가 나기 때문! 배열은 0부터 시작
}
return new String(cv_str);
}
public static void main(String[] args) {
String str = "Converts this string to a new character array.";
System.out.println("원본 str: " + str);
System.out.println("str의 역순: " + ConString(str));
}
}
▶Console |
원본 str: Converts this string to a new character array. str의 역순: .yarra retcarahc wen a ot gnirts siht strevnoC |
→ char는 문자를 하나씩 보기 때문에 역순으로 배열 가능