Java字符串类之间的转换
时间: 2024-06-02 15:14:04 浏览: 62
Java字符串类型转换
4星 · 用户满意度95%
在Java中,有三个主要的字符串类:String、StringBuffer和StringBuilder。这些类之间可以相互转换,具体方法如下:
1. String转换为StringBuffer或StringBuilder
String str = "Hello World";
StringBuffer sb = new StringBuffer(str);
StringBuilder sbd = new StringBuilder(str);
2. StringBuffer或StringBuilder转换为String
StringBuffer sb = new StringBuffer("Hello World");
StringBuilder sbd = new StringBuilder("Hello World");
String str1 = sb.toString();
String str2 = sbd.toString();
3. String转换为字符数组
String str = "Hello World";
char[] charArray = str.toCharArray();
4. 字符数组转换为String
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
String str = new String(charArray);
5. 字符数组转换为StringBuffer或StringBuilder
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
StringBuffer sb = new StringBuffer(charArray);
StringBuilder sbd = new StringBuilder(charArray);
6. StringBuffer或StringBuilder转换为字符数组
StringBuffer sb = new StringBuffer("Hello World");
StringBuilder sbd = new StringBuilder("Hello World");
char[] charArray1 = new char[sb.length()];
char[] charArray2 = new char[sbd.length()];
sb.getChars(0, sb.length(), charArray1, 0);
sbd.getChars(0, sbd.length(), charArray2, 0);
阅读全文