14StringBuider

1. StringBuider

1.1 StringBuilder概述

14StringBuider

String和StringBuilder的区别:

  • String:内容是不可变的
  • StringBuilder:内容是不可变的

1.2 StringBuilder的构造方法

14StringBuider

public class way_to_use {
    public static void main(String[] args) {
        //public StringBuilder():创建一个空白可变字符串对象,不含有任何内容
        StringBuilder sb= new StringBuilder();
        System.out.println("sb"+sb);
        System.out.println("sb.length:"+sb.length());

        //public StringBuilder(String str):根据字符串的内容,来创建可变字符串对象
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:"+sb2);
        System.out.println("sb2.length:"+sb2.length());
    }
}

1.3 StringBuilder的添加和反转方法

14StringBuider

        //添加和反转方法
        //public StringBuilder append(任意类型):添加数据,并返回对象本身
        StringBuilder sb= new StringBuilder();
        sb.append("hello");
        sb.append(200);

        //链式编程
        sb.append("hello").append(100);
        System.out.println("sb:"+sb);

        //public StringBuilder reverse():返回相反的字符序列
        sb.reverse();
        System.out.println(sb);

1.4 StringBuilder和String相互转换

14StringBuider

StringBuilder sb= new StringBuilder();
sb.append("hello");

//StringBuilder转String
String s = sb.toString();

//String 转 StringBuilder
String s = 'hello';
StringBuilder sb = new StringBuider(s);

案例:通过StringBuilder反转

14StringBuider

public class Reverse_StringBuilder {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一串字符串:");
        String s = sc.nextLine();

        String S_r = S_reverse(s);
        System.out.println("S_Reverse:"+S_r);
    }

    //调用方法:返回值:String  参数:字符串
    //过程:String - StringBuilder - reverse - String
    public static String S_reverse(String s){
        //方法一
/*      StringBuilder s1 = new StringBuilder(s);
        s1.reverse();
        String s2 = s1.toString();
        return s2;*/

        //方法二
        return new StringBuilder(s).reverse().toString();

    }
}

上一篇:StringBuffer,StringBuilder_听韩顺平课笔记


下一篇:StringBuilder 导致堆内存溢出