[Java] 基本数据、包装类间转换与处理

1. String

String是一个包装类

1.1 遍历足一取出里边的字符

    String s = "12345";
    for (int i = 0, len = s.length(); i < len; i++){
           char c = s.charAt(i)
    }

此时为char类型,如果需要转化为int,则需要调用Character的API

2. Char

基本数据类型

2.1 char 转 int

来源例子见1.1

通过包装类的自定义进制(如:10进制)方式进行转化为int
Character.digit(char ch, int radix)

    char c = '1'
    int digit = Character.digit(c, 10);

通过默认10进制数值方式转化为int
Character.getNumericValue(char ch)
与上面的调用底层代码是一样的,只是上面可以除了指定10进制还能指定其他进制

    int numericValue = Character.getNumericValue(c);

关于char的例子:

System.out.println("输出'0'~'9'的所有char类型字符(还是char类型)");
        for(char ch = '0'; ch <= '9'; ch++) {
            System.out.print(ch + " ");
        }
        System.out.println();

        System.out.println("输出'0'~'9'的所有char类型字符的int型字面值(int类型)");
        for(char ch = '0'; ch <= '9'; ch++) {
            System.out.print(Character.getNumericValue(ch) + " ");
        }
        System.out.println();

        System.out.println("输出'0'~'9'的所有char类型字符的ASCII值");
        for(char ch = '0'; ch <= '9'; ch++) {
            System.out.print((int)ch + " ");
        }
        System.out.println();

        System.out.println("输出'A'~'Z'的所有char类型字符");
        for(char ch = 'A'; ch <= 'Z'; ch++) {
            System.out.print(ch + " ");
        }
        System.out.println();

        System.out.println("输出'A'~'Z'的所有char类型字符的ASCII值");
        for(char ch = 'A'; ch <= 'Z'; ch++) {
            System.out.print((int)ch + " ");
        }
        System.out.println();

        System.out.println("输出'a'~'z'的所有char类型字符");
        for(char ch = 'a'; ch <= 'z'; ch++) {
            System.out.print(ch + " ");
        }
        System.out.println();

        System.out.println("输出'a'~'z'的所有char类型字符的ASCII值");
        for(char ch = 'a'; ch <= 'z'; ch++) {
            System.out.print((int)ch + " ");
        }
        System.out.println();

输出:

输出'0'~'9'的所有char类型字符(还是char类型)
0 1 2 3 4 5 6 7 8 9 
输出'0'~'9'的所有char类型字符的int型字面值(int类型)
0 1 2 3 4 5 6 7 8 9 
输出'0'~'9'的所有char类型字符的ASCII值
48 49 50 51 52 53 54 55 56 57 
输出'A'~'Z'的所有char类型字符
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
输出'A'~'Z'的所有char类型字符的ASCII值
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 
输出'a'~'z'的所有char类型字符
a b c d e f g h i j k l m n o p q r s t u v w x y z 
输出'a'~'z'的所有char类型字符的ASCII值
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 

参考:
https://blog.csdn.net/qauchangqingwei/arti...

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!