StringBuffer和String如何进行相互转换?

时间:2025-02-21 07:21:44

从String转换到StringBuffer:

1.通过StringBuffer的构造方法

 public static void main(String[] args) {
        String s = "hello";
        StringBuffer b = new StringBuffer(s);
    }

2.通过StringBuffer的append()方法

 public static void main(String[] args) {
        String s = "hello";
        StringBuffer b = new StringBuffer();
        (s);
    }
}

StringBuffer转换为String:

1.通过String构造方法

public static void main(String[] args) {
        String s = "hello";
        StringBuffer b = new StringBuffer();
        (s);
        String ss =new String(b);
    }

2.通过toString()方法

public static void main(String[] args) {
    String s = "hello";
    StringBuffer b = new StringBuffer(s);
    String ss = ();
   
}

3.使用substring方法

 public static void main(String[] args) {
        String s = "hello";
        StringBuffer b = new StringBuffer();
        (s);
        String y = (0,());
        (y);
    }