常见类---String类和StringBuffer类的相互转换

xiaoxiao2021-02-28  144

一.String—>StringBuffer类

方式: 通过有参构造通过无参构造创建字符串缓冲区对象,然后用append追加字符串举例: //String--->StringBuffer类转换 public class Demo8 { public static void main(String[] args) { //定义一个字符串 String s = "hello"; //报错,错误的转换方式 // StringBuffer sb = s; //报错,错误的方式 // StringBuffer sb = "hello"; //方式一:通过有参构造 StringBuffer sb1 = new StringBuffer(s); //方式二:通过无参构造,创建字符串缓冲区对象 StringBuffer sb2 = new StringBuffer(); sb2.append(s); System.out.println("sb1:"+sb1); System.out.println("sb2:"+sb2); } } 结果: sb1:hello sb2:hello

二.StringBuffer—>String类

方式: 有参构造方法toString()方法举例: //StringBuffer--->String public class Demo9 { public static void main(String[] args) { //创建字符串缓冲区对象 StringBuffer sb1 = new StringBuffer("hello"); //方式一:通过有参构造方法 String s = new String(sb1); //方式二:通过toString方法 String s2 = sb1.toString(); System.out.println(s); System.out.println(s2); } } 结果: hello hello
转载请注明原文地址: https://www.6miu.com/read-23605.html

最新回复(0)