常用API(一):StringBuilder (用StringBuilder操作字符串效率更高比String) StringBuffer(线程更安全) StringJoniner(比StringBuilder更适合拼接)

 

package com.itheima.StringBuilder1;

public class StringBuilder1 {
    public static void main(String[] args) {
        StringBuilder s=new StringBuilder();
        StringBuilder s1=new StringBuilder("pengsuoqun");//创建新字符串
        s1.append(12);
        s1.append("黑马");
        s1.append(true);//拼接各种数据

        System.out.println(s1);

        s1.reverse();//内容反转
        System.out.println(s1);

        String s3=s1.toString();//转字符串
        System.out.println(s3);
    }
}

测试StringBuilder性能与String的性能的代码,StringBuilder性能更强劲

 

 

package com.itheima.StringBuilder1;

public class StringBuilder1 {
    public static void main(String[] args) {
        //目标:掌握StringBuilder的好处
        //需求:要拼接100万次abc
        //先用tring测试看看性能
//        String s="";
//        for (int i = 0; i <1000000 ; i++) {
//            s=s+"abc";
//        }
//        System.out.println(s);

        StringBuilder s=new StringBuilder();
        for (int i = 0; i <1000000 ; i++) {
            s.append("abc");
        }
        System.out.println(s);
    }
}

 

2.

 3.

 

 

 

posted @ 2024-04-06 17:42  小彭先森  阅读(7)  评论(0编辑  收藏  举报