配列と文字列の変換

1104 ワード

配列を文字列に変換するのは簡単で、Stringクラスに存在する構造方法を使用して、直接変換します.メソッドを自分で定義して、配列の変換を実現することもできます.自己定義メソッド変換
public class Demo2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char[] arr = { 'l', 'i', 's', 'h', 'u', 'a', 'i', 'c', 'h' };
        for (int i = 0; i < 8; i++) {
            System.out.println(arr[i]);
        }
        String s = str(arr);
        System.out.println(s);
    }
    public static String str(char[] arr) {
        String s = " ";
        for (int i = 0; i < 8; i++) {
            s = s + arr[i];
        }
        return s;
        
    }
    
}

Stringコンストラクションメソッドを使用して変換
package com.lishuai.fuxi.www;

public class StringBufferTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char[] a = { 'l', 'i', 's', 's', 'h', 'k' };
        String str = new String(a);
        System.out.println(str);
    }

}