以下是在 Java 中將數組轉換為字符串的各種方法:
- Java Arrays.toString()用法及代碼示例:Arrays.toString() 方法用於返回指定數組內容的字符串表示形式。字符串表示由數組元素的列表組成,括在方括號 (“[]”) 中。相鄰元素由字符“, ”(逗號後跟一個空格)分隔。如果數組為空,則返回 “null”。
// Java program to demonstrate // working of Arrays.toString() import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { // Let us create different types of arrays and // print their contents using Arrays.toString() boolean[] boolArr = new boolean[] { true, true, false, true }; char[] charArr = new char[] { 'g', 'e', 'e', 'k', 's' }; double[] dblArr = new double[] { 1, 2, 3, 4 }; int[] intArr = new int[] { 1, 2, 3, 4 }; Object[] objArr = new Object[] { 1, 2, 3, 4 }; System.out.println( "Boolean Array:" + Arrays.toString(boolArr)); System.out.println( "Character Array:" + Arrays.toString(charArr)); System.out.println( "Double Array:" + Arrays.toString(dblArr)); System.out.println( "Integer Array:" + Arrays.toString(intArr)); System.out.println( "Object Array:" + Arrays.toString(objArr)); } }
輸出:Boolean Array:[true, true, false, true] Character Array:[g, e, e, k, s] Double Array:[1.0, 2.0, 3.0, 4.0] Integer Array:[1, 2, 3, 4] Object Array:[1, 2, 3, 4]
- Java StringBuilder append()用法及代碼示例:java.lang.StringBuilder.append(char[]) 是內置方法,它將 char 數組參數的字符串表示附加到此 StringBuilder 序列。
// Java program to illustrate the // StringBuilder.append(char[]) method import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuilder sbf = new StringBuilder("We are geeks "); System.out.println(sbf); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; // Appends string representation of char // array to this String Builder sbf.append(astr); System.out.println("Result after" + " appending = " + sbf); sbf = new StringBuilder("We are -"); System.out.println(sbf); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Appends string representation of char array to this StringBuilder */ sbf.append(astr); System.out.println("Result after appending = " + sbf); } }
輸出:We are geeks Result after appending = We are geeks GEEkS We are - Result after appending = We are -abcd
相關用法
- Java String轉String Array用法及代碼示例
- Java JSON Array轉String Array用法及代碼示例
- Java Character Array轉String用法及代碼示例
- Java Byte Array轉Hex String用法及代碼示例
- Java String轉Integer Array用法及代碼示例
- Java Hex String轉Byte Array用法及代碼示例
- Java Byte Array轉String用法及代碼示例
- Java java.sql.Date轉java.util.Date用法及代碼示例
- Java java.util.Date轉java.sql.Date用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 How to convert an Array to String in Java?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。