java 字符串与字符数组相互转化,字符串与字节数组相互转化

package com.liuxd;

/**
 * Created by Liuxd on 2018-11-02.
 */
public class TestString {


    public static void main(String[] args) throws Exception {
//        String str = "qingfengjian,yanyuedao";
        String str = "青锋剑,偃月刀";

        jdks(str);


    }

    /**
     * jdk
     */
    public static void jdks(String str) {
        //1、字符串转字符数组
        char[] chars = str.toCharArray();
        System.out.println("字符长度:" + chars.length);
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i] + "  ");
        }
        System.out.println();

        //2、字符数组转字符串
        String str2 = new String(chars);
        System.out.println("字符数组转字符串:" + str2);

        //3、字符串转字节数组
        byte[] bytes = str.getBytes();

        System.out.println("字节数组长度:" + bytes.length);
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i] + "  ");
        }
        System.out.println();

        //4、字节数组转字符串
        String result = new String(bytes);

        System.out.println("字节数组转字符串:" + result);

        System.out.println();
    }


}

执行结果: 

字符长度:7
青  锋  剑  ,  偃  月  刀  
字符数组转字符串:青锋剑,偃月刀
字节数组长度:21
-23  -99  -110  -23  -108  -117  -27  -119  -111  -17  -68  -116  -27  -127  -125  -26  -100  -120  -27  -120  -128  
字节数组转字符串:青锋剑,偃月刀

猜你喜欢

转载自blog.csdn.net/jiahao1186/article/details/83654779