Java之byte、char和String类型相互转换

 

 1 package basictype;
 2 
 3 /**
 4  * byte、char和String类型相互转换
 5  */
 6 public class CHJavaType {
 7     public static void main(String[] args) {
 8         String string = "abcd";
 9 
10         // String转char[]
11         char[] chars = string.toCharArray();
12         for (char c : chars) {
13             System.out.println(c);
14         }
15         // char[]转String
16         System.out.println("String.valueOf:" + String.valueOf(chars));
17         System.out.println("new String:" + new String(chars));
18 
19         byte[] bytes = {};
20         try {
21             // String转byte[]
22             bytes = string.getBytes("UTF-8");
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26 
27         // byte[]转String
28         System.out.println(new String(bytes));
29     }
30 }

 

posted @ 2018-02-13 14:58  星瑞  阅读(488)  评论(0编辑  收藏  举报