char 关键字

概述

char 是Java中的基本数据类型,表示16位Unicode字符,取值范围为0到65535('\u0000'到'\uffff')。

语法格式

char variableName;                // 声明char变量
char variableName = 'A';          // 字符字面量
char variableName = 65;           // Unicode码值
char variableName = '\u0041';     // Unicode转义序列

基本特性

public class CharBasicsExample {
    public static void main(String[] args) {
        // 字符字面量
        char c1 = 'A';
        char c2 = '中';
        char c3 = '9';
        char c4 = '@';

        System.out.println("字符: " + c1 + ", Unicode码: " + (int)c1);
        System.out.println("字符: " + c2 + ", Unicode码: " + (int)c2);
        System.out.println("字符: " + c3 + ", Unicode码: " + (int)c3);
        System.out.println("字符: " + c4 + ", Unicode码: " + (int)c4);

        // Unicode码值直接赋值
        char unicode1 = 65;      // 'A'
        char unicode2 = 20013;   // '中'
        char unicode3 = 57;      // '9'

        System.out.println("从码值65: " + unicode1);
        System.out.println("从码值20013: " + unicode2);
        System.out.println("从码值57: " + unicode3);

        // Unicode转义序列
        char escape1 = '\u0041';  // 'A'
        char escape2 = '\u4e2d';  // '中'
        char escape3 = '\u0039';  // '9'

        System.out.println("转义序列\\u0041: " + escape1);
        System.out.println("转义序列\\u4e2d: " + escape2);
        System.out.println("转义序列\\u0039: " + escape3);

        // 常量值
        System.out.println("char最小值: " + (int)Character.MIN_VALUE);
        System.out.println("char最大值: " + (int)Character.MAX_VALUE);
        System.out.println("char大小(位): " + Character.SIZE);
        System.out.println("char大小(字节): " + (Character.SIZE / 8));
    }
}

转义字符

public class CharEscapeExample {
    public static void main(String[] args) {
        // 常用转义字符
        char tab = '\t';        // 制表符
        char newline = '\n';    // 换行符
        char carriageReturn = '\r'; // 回车符
        char backspace = '\b';  // 退格符
        char formFeed = '\f';   // 换页符
        char singleQuote = '\''; // 单引号
        char doubleQuote = '\"'; // 双引号
        char backslash = '\\';   // 反斜杠

        System.out.println("制表符:" + tab + "结束");
        System.out.println("换行符前" + newline + "换行符后");
        System.out.println("单引号: " + singleQuote);
        System.out.println("双引号: " + doubleQuote);
        System.out.println("反斜杠: " + backslash);

        // 八进制转义
        char octal = '\101';    // 八进制101 = 十进制65 = 'A'
        System.out.println("八进制\\101: " + octal);

        // 特殊的零字符
        char nullChar = '\0';   // 空字符
        System.out.println("空字符码值: " + (int)nullChar);

        // 创建包含转义字符的字符串
        String text = "第一行\n第二行\t制表符\n第三行";
        System.out.println("包含转义字符的字符串:");
        System.out.println(text);
    }
}

字符分类和判断

public class CharClassificationExample {
    public static void main(String[] args) {
        char[] chars = {'A', 'a', '5', ' ', '@', '中', '\n', '\t'};

        System.out.println("字符分类分析:");
        System.out.println("字符\t码值\t字母\t数字\t空白\t大写\t小写\t汉字");

        for (char c : chars) {
            System.out.printf("%c\t%d\t%s\t%s\t%s\t%s\t%s\t%s%n",
                c,
                (int)c,
                Character.isLetter(c) ? "是" : "否",
                Character.isDigit(c) ? "是" : "否",
                Character.isWhitespace(c) ? "是" : "否",
                Character.isUpperCase(c) ? "是" : "否",
                Character.isLowerCase(c) ? "是" : "否",
                isChinese(c) ? "是" : "否"
            );
        }

        // 更多分类方法
        char testChar = 'A';
        System.out.println("\n字符 '" + testChar + "' 的详细分析:");
        System.out.println("是字母数字: " + Character.isLetterOrDigit(testChar));
        System.out.println("是Java标识符开始: " + Character.isJavaIdentifierStart(testChar));
        System.out.println("是Java标识符部分: " + Character.isJavaIdentifierPart(testChar));
        System.out.println("是ISO控制字符: " + Character.isISOControl(testChar));
        System.out.println("Unicode类别: " + Character.getType(testChar));
    }

    // 判断是否为中文字符
    private static boolean isChinese(char c) {
        return c >= 0x4e00 && c <= 0x9fff;
    }
}

字符操作和转换

public class CharOperationExample {
    public static void main(String[] args) {
        // 大小写转换
        char lower = 'a';
        char upper = 'Z';

        System.out.println("'" + lower + "' 转大写: '" + Character.toUpperCase(lower) + "'");
        System.out.println("'" + upper + "' 转小写: '" + Character.toLowerCase(upper) + "'");

        // 数字字符转换
        char digit = '7';
        int numericValue = Character.getNumericValue(digit);
        System.out.println("字符 '" + digit + "' 的数值: " + numericValue);

        // 从数字创建字符
        for (int i = 0; i <= 9; i++) {
            char digitChar = Character.forDigit(i, 10);
            System.out.println("数字 " + i + " 的字符: '" + digitChar + "'");
        }

        // 字符算术
        char a = 'A';
        char z = 'Z';
        System.out.println("从 'A' 到 'Z':");
        for (char c = a; c <= z; c++) {
            System.out.print(c + " ");
            if ((c - a + 1) % 13 == 0) System.out.println(); // 每13个字符换行
        }

        // 字符比较
        char char1 = 'B';
        char char2 = 'A';
        System.out.println("\n字符比较:");
        System.out.println("'" + char1 + "' > '" + char2 + "': " + (char1 > char2));
        System.out.println("'" + char1 + "' - '" + char2 + "' = " + (char1 - char2));
    }
}

字符数组和字符串

public class CharArrayStringExample {
    public static void main(String[] args) {
        // 字符数组
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};
        System.out.println("字符数组: " + java.util.Arrays.toString(charArray));

        // 字符数组转字符串
        String fromCharArray = new String(charArray);
        System.out.println("从字符数组创建字符串: " + fromCharArray);

        // 字符串转字符数组
        String str = "World";
        char[] fromString = str.toCharArray();
        System.out.println("从字符串创建字符数组: " + java.util.Arrays.toString(fromString));

        // 访问字符串中的字符
        String text = "Java Programming";
        System.out.println("字符串 \"" + text + "\" 中的字符:");
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            System.out.println("  索引 " + i + ": '" + c + "' (Unicode: " + (int)c + ")");
        }

        // 字符频率统计
        String sample = "Hello World";
        int[] frequency = new int[256]; // ASCII字符范围

        for (char c : sample.toCharArray()) {
            if (c < 256) {
                frequency[c]++;
            }
        }

        System.out.println("\n\"" + sample + "\" 字符频率:");
        for (int i = 0; i < frequency.length; i++) {
            if (frequency[i] > 0) {
                System.out.println("  '" + (char)i + "': " + frequency[i] + "次");
            }
        }
    }
}

Unicode和国际化

public class CharUnicodeExample {
    public static void main(String[] args) {
        // 不同语言的字符
        char[] internationalChars = {
            'A',        // 英文
            'Ñ',        // 西班牙文
            'ü',        // 德文
            'α',        // 希腊文
            'Ж',        // 俄文
            'あ',       // 日文平假名
            'カ',       // 日文片假名
            '한',       // 韩文
            '中',       // 中文
            '🙂'        // 表情符号(需要代理对处理)
        };

        System.out.println("国际化字符示例:");
        for (char c : internationalChars) {
            if (Character.isValidCodePoint(c)) {
                System.out.printf("字符: %c, Unicode: U+%04X, 类别: %d%n", 
                    c, (int)c, Character.getType(c));
            }
        }

        // Unicode块信息
        char chineseChar = '中';
        Character.UnicodeBlock block = Character.UnicodeBlock.of(chineseChar);
        System.out.println("\n字符 '" + chineseChar + "' 属于Unicode块: " + block);

        // 代理对处理(用于处理超过16位的Unicode字符)
        String emoji = "🙂😊🎉";
        System.out.println("\n表情符号字符串: " + emoji);
        System.out.println("字符串长度(char单位): " + emoji.length());

        int codePointCount = emoji.codePointCount(0, emoji.length());
        System.out.println("实际字符数(码点): " + codePointCount);

        // 遍历码点
        System.out.println("逐个码点:");
        for (int i = 0; i < emoji.length();) {
            int codePoint = emoji.codePointAt(i);
            System.out.printf("  码点: U+%X, 字符: %s%n", 
                codePoint, new String(Character.toChars(codePoint)));
            i += Character.charCount(codePoint);
        }
    }
}

实际应用示例

import java.util.*;

public class CharApplicationExample {

    // 密码强度检查
    public static void checkPasswordStrength(String password) {
        boolean hasUpper = false;
        boolean hasLower = false;
        boolean hasDigit = false;
        boolean hasSpecial = false;

        for (char c : password.toCharArray()) {
            if (Character.isUpperCase(c)) {
                hasUpper = true;
            } else if (Character.isLowerCase(c)) {
                hasLower = true;
            } else if (Character.isDigit(c)) {
                hasDigit = true;
            } else if (!Character.isWhitespace(c)) {
                hasSpecial = true;
            }
        }

        System.out.println("密码: " + password);
        System.out.println("长度: " + password.length());
        System.out.println("包含大写字母: " + hasUpper);
        System.out.println("包含小写字母: " + hasLower);
        System.out.println("包含数字: " + hasDigit);
        System.out.println("包含特殊字符: " + hasSpecial);

        int strength = 0;
        if (password.length() >= 8) strength++;
        if (hasUpper) strength++;
        if (hasLower) strength++;
        if (hasDigit) strength++;
        if (hasSpecial) strength++;

        String[] levels = {"很弱", "弱", "一般", "强", "很强"};
        System.out.println("密码强度: " + levels[Math.min(strength, 4)]);
    }

    // 凯撒密码加密
    public static String caesarCipher(String text, int shift) {
        StringBuilder result = new StringBuilder();

        for (char c : text.toCharArray()) {
            if (Character.isLetter(c)) {
                char base = Character.isUpperCase(c) ? 'A' : 'a';
                char encrypted = (char) ((c - base + shift) % 26 + base);
                result.append(encrypted);
            } else {
                result.append(c);
            }
        }

        return result.toString();
    }

    // 字符统计分析
    public static void analyzeText(String text) {
        int letters = 0, digits = 0, spaces = 0, others = 0;
        Map<Character, Integer> charCount = new HashMap<>();

        for (char c : text.toCharArray()) {
            if (Character.isLetter(c)) {
                letters++;
            } else if (Character.isDigit(c)) {
                digits++;
            } else if (Character.isWhitespace(c)) {
                spaces++;
            } else {
                others++;
            }

            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }

        System.out.println("文本分析: \"" + text + "\"");
        System.out.println("总字符数: " + text.length());
        System.out.println("字母: " + letters);
        System.out.println("数字: " + digits);
        System.out.println("空白: " + spaces);
        System.out.println("其他: " + others);

        System.out.println("字符频率前5:");
        charCount.entrySet().stream()
            .sorted(Map.Entry.<Character, Integer>comparingByValue().reversed())
            .limit(5)
            .forEach(entry -> 
                System.out.println("  '" + entry.getKey() + "': " + entry.getValue() + "次"));
    }

    public static void main(String[] args) {
        System.out.println("=== 密码强度检查 ===");
        checkPasswordStrength("password");
        System.out.println();
        checkPasswordStrength("Password123!");

        System.out.println("\n=== 凯撒密码 ===");
        String plaintext = "Hello World";
        String encrypted = caesarCipher(plaintext, 3);
        String decrypted = caesarCipher(encrypted, -3);

        System.out.println("原文: " + plaintext);
        System.out.println("加密: " + encrypted);
        System.out.println("解密: " + decrypted);

        System.out.println("\n=== 文本分析 ===");
        analyzeText("Hello World! 123 你好世界!");
    }
}

最佳实践

public class CharBestPractices {

    // 1. 字符比较最佳实践
    public static boolean isVowel(char c) {
        // 转换为小写后比较,避免重复代码
        char lower = Character.toLowerCase(c);
        return lower == 'a' || lower == 'e' || lower == 'i' || 
               lower == 'o' || lower == 'u';
    }

    // 2. 安全的字符范围检查
    public static boolean isInRange(char c, char start, char end) {
        return c >= start && c <= end;
    }

    // 3. 字符到字符串的转换
    public static String charToString(char c) {
        // 推荐方式
        return String.valueOf(c);

        // 避免使用连接操作
        // return "" + c;  // 效率较低
    }

    // 4. 处理特殊字符
    public static String sanitizeInput(String input) {
        StringBuilder result = new StringBuilder();

        for (char c : input.toCharArray()) {
            if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {
                result.append(c);
            } else {
                // 替换特殊字符为下划线
                result.append('_');
            }
        }

        return result.toString();
    }

    // 5. Unicode安全处理
    public static void printSafeChar(char c) {
        if (Character.isDefined(c) && !Character.isISOControl(c)) {
            System.out.println("字符: " + c);
        } else {
            System.out.println("不可打印字符,码值: " + (int)c);
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 元音判断 ===");
        char[] testChars = {'A', 'e', 'X', 'o', 'Z'};
        for (char c : testChars) {
            System.out.println("'" + c + "' 是元音: " + isVowel(c));
        }

        System.out.println("\n=== 范围检查 ===");
        System.out.println("'M' 在 A-Z 范围: " + isInRange('M', 'A', 'Z'));
        System.out.println("'5' 在 0-9 范围: " + isInRange('5', '0', '9'));

        System.out.println("\n=== 输入清理 ===");
        String input = "Hello@World#2023!";
        String cleaned = sanitizeInput(input);
        System.out.println("原始: " + input);
        System.out.println("清理后: " + cleaned);

        System.out.println("\n=== 安全字符打印 ===");
        printSafeChar('A');
        printSafeChar('\n');
        printSafeChar('中');
    }
}

char类型是Java处理文本和字符数据的基础,在字符串处理、文本分析、编码转换等场景中发挥重要作用。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""