整理:字串和陣列的轉化
阿新 • • 發佈:2019-01-05
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
String myWord = "aaa bbb ccc";
String[] strings = myWord.split("");
System.out.println(strings); //[Ljava.lang.String;@1540e19d
System.out.println(Arrays.toString(strings)); //[a, a, a, , b, b, b, , c, c, c]
char[] chars = myWord.toCharArray();
System.out.println(chars); //aaa bbb ccc
System.out.println(chars.toString()); //[ [email protected]
System.out.println(Arrays.toString(chars)); //[a, a, a, , b, b, b, , c, c, c]
System.out.println(String.valueOf(chars)); //aaa bbb ccc
String myWord2 = "111 222 333";
String[] strings2 = myWord2.split("");
System.out.println(strings2); //[Ljava.lang.String;@14ae5a5
System.out.println(Arrays.toString(strings2)); //[1, 1, 1, , 2, 2, 2, , 3, 3, 3]
char[] chars2 = myWord2.toCharArray();
System.out.println(chars2); //111 222 333
System.out.println(chars2.toString()); //[ [email protected]
System.out.println(Arrays.toString(chars2)); //[1, 1, 1, , 2, 2, 2, , 3, 3, 3]
System.out.println(String.valueOf(chars2)); //111 222 333
int[] ints = new int[]{1,2,3,4};
System.out.println(ints.toString()); //[[email protected]
System.out.println(Arrays.toString(ints)); //[1, 2, 3, 4]
System.out.println(String.valueOf(ints)); //[ [email protected]
}
}
如果要把字串變成陣列:
第一種方法:先split,將字串變為字串陣列,這樣列印是以字串的形式列印,再Arrays.toString(字串陣列),這樣列印是以陣列的形式列印;
第二種方法:字串.toCharArray(),生成字元陣列。
如果要把字元陣列變成字串:
第一種方法:Arrays.toString(字元陣列);
第二種方法:String.valueOf(字元陣列);
如果要把整型陣列變成字串:
Arrays.toString(整型陣列);
關於輸出:
public class Solution {
public static void main(String[] args) {
char[] chars = new char[]{'a', 'b', 'c'};
int[] ints = new int[]{1,2,3};
String[] strings = new String[]{"aaa", "bbb", "ccc"};
System.out.println(chars); //abc
System.out.println(ints); //[[email protected]
System.out.println(strings); //[Ljava.lang.String;@677327b6
}
}
System.out.println(char陣列):輸出的是char陣列的內容
System.out.println(其他型別的陣列):當作Object型別處理,自動呼叫了String.valueOf()方法,輸出的是getClass().getName() + '@' + Integer.toHexString(hashCode()),即陣列hash碼的字串表示形式,作為16位中的無符號整數。