
1) String은 Char로 쪼갤 수 있고, 각각의 Char은 아스키 코드로 변환할 수 있다.
2) 아스키 코드를 반복문 등에 넣어 문자를 이용한 조건문을 만들 수 있다.
.charAt() : 한 글자만 가져오기
.toCharArray() : 모든 글자를 Char 배열에 넣기
str.charAt(idx) 로 character 가져오기
String str = "ABCCAAB";
// 각각 요소 출력
System.out.println(str.charAt(0)); //A
System.out.println(str.charAt(1)); //B
System.out.println(str.charAt(2)); //C
String str = "ABCCAAB";
// 아스키 코드로 변경하기
System.out.println((int) str.charAt(0)); // 65
System.out.println((int) str.charAt(1)); //66
System.out.println((int) str.charAt(2)); //67
문자를 아스키 코드로 변경하고자 한다면 명시적 형변환을 이용하여 변경할 수 있습니다
int numArr[] = {104, 101, 108, 108, 111};
char[] charArr = new char[numArr.length];
// int to String
for (int i = 0; i < numArr.length; i++) {
charArr[i] = (char) numArr[i];
}
log.debug("resultIntArr2 :: " + Arrays.toString(charArr)); // [h, e, l, l, o]
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String str = "ABCCAAB";
// 각각 요소 출력
System.out.println(str.charAt(0));
System.out.println(str.charAt(1));
System.out.println(str.charAt(2));
// 아스키 코드로 변경하기
System.out.println((int) str.charAt(0));
System.out.println((int) str.charAt(1));
System.out.println((int) str.charAt(2));
// 0에 A 저장하고,
// 1에 B 저장하고,
// 2에 C 저장하고,
// 이런식으로 알파벳 순서대로 저장하기
int[] alphabet = new int[3];
System.out.println(str.charAt(0) - 'A');
System.out.println(str.charAt(1) - 'A');
System.out.println(str.charAt(2) - 'A');
// 알파벳의 빈도수 구하기
for (int i = 0; i < str.length(); i++) {
int idx = str.charAt(i) - 'A';
alphabet[idx]++;
}
System.out.println(Arrays.toString(alphabet));
}
}
만약 예를 들어, 'B' 가 있다고 합시다.
B의 아스키 코드는 66 입니다. B는 알파벳에서 두번째에 해당하는 문자입니다.
만약 이를 두번째로 변경하고자 한다면, 'B' - 'A' 를 하면 1로 나옵니다.
왜나하면 'A'의 아스키코드는 65이기 때문입니다.
문자들 사이의 마이너스 연산때문에 아스키 코드로 변경이 되어 숫자가 return 됩니다.
System.out.println('B' - 'A'); // 1
https://yeomss.tistory.com/336#-int-%--%EB%A-%-C%--%EC%--%--%EC%-A%A-%ED%--%A-%--%EC%BD%--%EB%--%-C%EB%A-%-C%--%EB%B-%--%EA%B-%BD%ED%--%--%EA%B-%B-
https://adjh54.tistory.com/117