public class StringTest {
//String类型转变为char类型
@Test
public void test1(){
String str = "abc";
char[] chars = str.toCharArray();
for (int i = 0; i <chars.length ; i++) {
System.out.println(chars[i]);
}
}
//String类型转变为byte类型
@Test
public void test2(){
String str = "abc";
byte[] chars = str.getBytes();
for (int i = 0; i <chars.length ; i++) {
System.out.println(chars[i]);
}
}
@Test
public void test3() throws Exception{
String str = "abc中国";
byte[] chars = str.getBytes("gbk"); //默认使用utf-8编码
for (int i = 0; i <chars.length ; i++) {
System.out.println(chars[i]);
}
}
@Test
public void test4() throws Exception{
String str = "abc中国";
byte[] bytes = str.getBytes(); //使用默认utf-8编码
System.out.println(Arrays.toString(bytes));
String s = new String(bytes); //使用默认utf-8解码
System.out.println(s);
String s1 = new String(bytes,"gbk"); //使用gbk对使用utf-8编码的bytes解码,出现乱码错误
System.out.println(s1);
}
}
关于String类中的类型转换一些方法
最新推荐文章于 2022-12-05 13:05:09 发布