字符串與字符數組的多種轉換方式。


public class StringAPIDemo1 {
public static void main(String[] args) {
String str = "HELLO";
char c[] = str.toCharArray(); // 將字符串變為字符數組

for (int i = 0; i < c.length; i++) {
System.out.print(c[i] + "\t");
}
System.out.println(); //換行
String str2 = new String(c);// 將整個字符數組轉換為字符串
String str3 = new String(c, 0, 3);// 將部分字符數組轉換為字符串
System.out.println(str2);
System.out.println(str3);
}

private static void test2() {
String str1 = "霍元甲";
byte b[] = str1.getBytes();// 將字符串轉為byte數組
System.out.println(new String(b)); // 將整個byte數組轉換為字符串
System.out.println(new String(b, 0, 3)); // 將部分byte數組轉換為字符串
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}

}


}


}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM