Java中字符串轉換爲字符串數組
第一種:轉換爲char類型數組
String str = "Hello World";
char [] chars= str.toCharArray();
System.out.println(chars);
輸出結果爲
Hello World
第二種:轉換爲byte
//用getBytes
String str = "Hello World";
byte []bytes=str.getBytes();
System.out.println(bytes);
*當將輸入的字符串轉換爲字符串數組時
//需要用nextLine 否則只能輸出空格之前的字符串
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();
char[] array = a.toCharArray();
*當字符串數組轉換爲字符串時
StringBuffer sb = new StringBuffer();
String[] str = {"hello", "world"};
for(int i = 0; i < str.length; i++){
sb. append(str[i]);
}
String s = sb.toString();
*當char數組轉換爲字符串時
char[] chars={'H','e','l','l','o'};
String str=new String(chars);