Java String,char,int类型的相互转换

7 篇文章 1 订阅
6 篇文章 2 订阅

1. int转string(三种方法)

public static void main(String[] args) {
        //int -> string
        int testInt = 10;

        String testString1 = testInt + "";
        System.out.println("string1:  " +testString1);

        String testString2 = String.valueOf(testInt);
        System.out.println("string2:  " +testString2);

        String testString3 = Integer.toString(testInt);
        System.out.println("string3:  " +testString3);
}

输出结果:

string1:  10
string2:  10
string3:  10

2.0~9的int数字转为char(两种方法)

public static void main(String[] args) {
        //int -> char
        int testInt = 4;

        char testChar1 = (char) (testInt + '0');
        System.out.println(testChar1);

        //代表10进制
        int radix = 10;
        char testChar2 = Character.forDigit(testInt, radix);
        System.out.println(testChar2);
}

输出结果:

4
4

 

3.string转int的方法(两种方法)

public static void main(String[] args) {

        //string -> int
        String testString = "520";

        int testInt1 = Integer.parseInt(testString);
        System.out.println("int1:  " +testInt1);

        int testInt2 = Integer.valueOf(testString);
        System.out.println("int2:  " +testInt2);

}

输出结果为:

int1:  520
int2:  520

4.string转char的方法

public static void main(String[] args) {

        // string -> char
        String testString = "abcdefg";

        //获取某个下标的字符元素
        char ch = testString.charAt(0);
        System.out.println("ch:   " + ch);

        //string转 char array
        char chArray[] = testString.toCharArray();
        System.out.println("ch:   " + chArray[0]);
    }

输出结果为:

ch:   a
ch:   a

5. char转int (两种方法)

public static void main(String[] args) {

        // char转 int
        char ch = '9';

        int testInt1 = Character.getNumericValue(ch);

        int testInt2 = (int)ch - (int)'0';

        System.out.println("int:    "+ testInt1);
        System.out.println("int:    "+ testInt2);

    }

输出结果:

int:    9
int:    9

6.char转string方法(四种方法)

public static void main(String[] args) {

        // char转 string
        char ch = 's';

        String testString1 = String.valueOf(ch);
        System.out.println("string:    "+ testString1);

        String testString2 = ch + "";
        System.out.println("string:    "+ testString2);

        String testString3 = Character.toString(ch);
        System.out.println("string:    "+ testString3);

        String testString4= String.valueOf(new char[]{'j', 'a', 'v', 'a'});
        System.out.println("string:    "+ testString4);

    }

输出结果为:

string:    s
string:    s
string:    s
string:    java

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值