// 第 4 周 – 字符编码：char、码点、UTF-8 字节
// 运行：java Encoding.java
import java.nio.charset.StandardCharsets;

public class Encoding {
    public static void main(String[] args) {
        String s = "Aé世😀";

        // Java 的 String 内部由 UTF-16 代码单元（char）组成。
        // BMP 之外的字符（例如表情符号）占两个 char（代理对）。
        System.out.println("length()          = " + s.length());                         // 5
        System.out.println("codePointCount()  = " + s.codePointCount(0, s.length()));   // 4
        System.out.println("number of UTF-8 bytes = " + s.getBytes(StandardCharsets.UTF_8).length); // 10

        // 按码点遍历 – 每个“真正的”字符访问一次
        s.codePoints().forEach(cp ->
                System.out.printf("  %s  U+%04X  (%d)%n", new String(Character.toChars(cp)), cp, cp));

        // 打印 UTF-8 字节
        System.out.print("UTF-8: ");
        for (byte b : s.getBytes(StandardCharsets.UTF_8)) System.out.printf("%02X ", b);
        System.out.println();

        // 逐个 char 遍历会把表情符号切成两“半”!
        System.out.print("char by char: ");
        for (int i = 0; i < s.length(); i++) System.out.printf("%04X ", (int) s.charAt(i));
        System.out.println();

        // ASCII 运算
        char c = 'c';
        System.out.println("'c' - 'a' = " + (c - 'a') + " (position of the letter in the alphabet)");
        System.out.println("'7' - '0' = " + ('7' - '0') + " (digit character -> value)");
    }
}
