1. 程式人生 > >java 字串與字元陣列相互轉化,字串與位元組陣列相互轉化

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  
位元組陣列轉字串:青鋒劍,偃月刀