Java常用类—— String、StringBuffer、StringBuilder 的区别

一、String

1、概述

  • 字符串是由多个字符组成的一串数据
  • 字符串可以看成字符数组

2、构造方法

  • offset:抵消、弥补
  • original:起初的、原来的
  • public String()
  • public String(byte[] bytes)
  • public String(byte[] bytes,int offset, int length)
  • public String(char value)
  • public String(char value,int offset,int count)
  • public String(String original)

案例:新建 StringDm.java 文件

package zifuchuan;

public class StringDm {
    public static void main(String[] args){
        String s1 = new String();
        System.out.println(s1);
        System.out.println(s1.length());
        System.out.println("---------------");
        
        byte[] b = {1,4,5,9,12};
        String s2 = new String(b);
        System.out.println(s2);
        System.out.println(s2.length());
        System.out.println("+++++++++++++++");

        String s3 = new String(b,1,3);//从第二个值开始,长度是3个
        System.out.println(s3);
        System.out.println(s3.length());
        System.out.println("++++++++------------");

        char[] c = {'l','o','v','e','苍','井','空'};//定义字符数组
        String s4 = new String(c);//把字符转换成字符串
        System.out.println(s4);//输出字符串
        System.out.println(s4.length());//输出字符串长度
        String s5 = new String(c,4,3);//把字符中从第5个字符开始,总共3个字符,转换成字符串
        System.out.println(s5);//输出:苍井空
        System.out.println(s5.length());//长度是3
        System.out.println("_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+");

        String s6 = new String("波多野结衣的声音很好听");//把字符串常量值转换成字符串
        System.out.println(s6);
        System.out.println(s6.length());

        String s7 = "波多野结衣的声音很好听";//定义一个字符串
        System.out.println(s7);//和s6的值相等
        System.out.println(s7.length());
    }
}

在上面的案例中,s6 和 s7 的区别:

package zifuchuan;

public class StringDm {
    public static void main(String[] args){
        String s6 = new String("波多野结衣的声音很好听");//把字符串常量值转换成字符串
        System.out.println(s6);
        System.out.println(s6.length());

        String s7 = "波多野结衣的声音很好听";//定义一个字符串
        System.out.println(s7);//和s6的值相等
        System.out.println(s7.length());
        System.out.println("-----------------------------");

        String s8 =  new String("波多野结衣的声音很好听");//把字符串常量值转换成字符串
        System.out.println(s6 == s8);//s6不等于s8,每次在堆里产生对象,内存地址不相等,false
        System.out.println(s6.intern() == s8.intern());//intern 得到对象对应的常量池中的对象,true
        System.out.println(s6.intern() == s7);//true
        System.out.println(s6 == s7);//false
        System.out.println(s6.equals(s7));//true
    }
}

3、特点

  • 字符串是常量,它的值创建后不能被更改
package zifuchuan;

public class StringDm {
    public static void main(String[] args){
        String s1 = "小泽玛利亚";
        String s2 = "很漂亮";
        String s3 = "小泽玛利亚很漂亮";
        System.out.println(s1 + s2 == s3);//false
        System.out.println(s3.equals((s1 + s2)));//true
        System.out.println("-------------------");

        System.out.println(s3 == "小泽玛利亚"+"很漂亮")//true;
        System.out.println(s3.equals("小泽玛利亚"+"很漂亮"));//true
        System.out.println("+++++++++++++++++++++++++");

        System.out.println(s3 == "小泽玛利亚很漂亮");//true
        System.out.println(s3.equals("小泽玛利亚"+"很漂亮"));//true
    }
}

4、String 类的判断功能

  • equals:相等
  • equalsIgnoreCase:相等符号或大小写
  • contains:包含
  • boolean equals(Object obj)//比较字符串内容是否相等,区分大小写
  • boolean equalsIgnoreCase(String str)//比较字符串内容是否相等,忽略大小写
  • boolean contains(String str)//判断大写字符串中是否包含小写
  • boolean startWith(String str)//判断字符串中是否以指定的字符开头
  • boolean endsWith(String str)//判断字符串中是否以指定的字符结尾
  • boolean isEmpty()//判断字符串是否为空
package zifuchuan;

public class StringDm {
    public static void main(String[] args){
        String s1 = "helloworld";
        String s2 = "helloworld";
        String s3 = "HelloWorld";

        // boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
        System.out.println("equals:" + s1.equals(s2)); //true
        System.out.println("equals:" + s1.equals(s3)); //false
        System.out.println("-----------------------");

        // boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
        System.out.println("equals:" + s1.equalsIgnoreCase(s2)); //true
        System.out.println("equals:" + s1.equalsIgnoreCase(s3)); //true
        System.out.println("+++++++++++++++++++++++");

        // boolean contains(String str):判断大字符串中是否包含小字符串
        System.out.println("contains:" + s1.contains("hello")); //true
        System.out.println("contains:" + s1.contains("hw")); //false
        System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=");

        // boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
        System.out.println("startsWith:" + s1.startsWith("h")); //true
        System.out.println("startsWith:" + s1.startsWith("hello")); //true
        System.out.println("startsWith:" + s1.startsWith("world")); //flase
        System.out.println("_+_+_+_+_+_+_+_+_+_+_+_+_+_+_");

        // boolean isEmpty():判断字符串是否为空。
        System.out.println("isEmpty:" + s1.isEmpty()); //false

        String s4 = "    ";
        String s5 = null;
        System.out.println("isEmpty:" + s4.isEmpty());
        // NullPointerException
        // s5对象都不存在,所以不能调用方法,空指针异常
//		System.out.println("isEmpty:" + s5.isEmpty());
        if (null != s3 && !s3.trim().equals("")) {
            System.out.println("字符串对象不为空判断....");
        }
    }
}

5、String 类的获取功能

  • indexOf:索引
  • fromIdex:源索引
  • substring:子字符串
  • int length()
  • char charAt(int index)//获取字符串的长度。
  • int indexOf(int ch)//返回指定字符在此字符串中第一次出现处的索引。
  • int indexOf(String str)//返回指定字符串在此字符串中第一次出现处的索引。
  • int indexOf(int ch,int fromIndex)//返回指定字符在此字符串中从指定位置后第一次出现处的索引。
  • int indexOf(String str,int fromIndex)//返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
  • String substring(int start)//从指定位置开始截取字符串,默认到末尾。
  • String substring(int start,int end)//从指定位置开始到指定位置结束截取字符串。

6、String 类的替换功能

  • String replace(char old,char new)
  • String replace(String old,String new)

7、String 类去除空格

  • String trim()

8、String 类按字典顺序比较两个字符串

  • compare:比较
  • IgnoreCase:忽略
  • int compareTo(String str)
  • int compareToIgnoreCase(String str)

9、猜数字小游戏代码

package zifuchuan;

import java.util.Scanner;

public class GuessNumberGame {
    private GuessNumberGame(){}//定义构造函数
    public static void start(){
        int n = (int)(Math.random() * 100) + 1;//获取一个随机数(1—100),不包含100
        while(true){
            Scanner s = new Scanner(System.in);//输入一个数组
            System.out.println("请输入一个数子(1-100):");
            int shu = s.nextInt();
            //判断
            if (shu > n){
                System.out.println("您猜的数字是:"+shu+",猜大了,请重新猜!!");
            }else if (shu < n){
                System.out.println("您猜的数字是:"+shu+",猜小了,请重新猜!!");
            }else{
                System.out.println("恭喜您猜中了");
                break;
            }
        }
    }
    public static void main(String[] args){
        //System.out.println((int)(Math.random() * 100) + 1);
        start();
    }
}

10、模拟登录,给三次机会,并提示还有几次

package zifuchuan;

import java.util.Scanner;

public class SignIn {
    public static void main(String[] args){
        String username = "admin";
        String password = "admin";
        //给三次机会
        for(int i = 0; i < 3; i++){
            Scanner s = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String u = s.nextLine();
            System.out.println("请输入密码:");
            String p = s.nextLine();

            //判断用户名和密码是否正确
            if (u.equals(username) && p.equals(password)){
                System.out.println("登录成功!!");
                break;
            }else{
                if ((2 - i) == 0){
                    System.out.println("账号被锁定,请与客服联系!!");
                }else{
                    System.out.println("登录失败,您还有"+(3-i)+"次机会,请重新登录!!");
                }
            }
        }
    }
}

11、统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

package zifuchuan;

public class StringDm {
    public static void main(String[] args){
        String s = "HelloLemon4317622";//定义一个字符,大写2个,小写8个,数字7个

        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;

        for (int i = 0; i < s.length(); i++){
            char c = s.charAt(i);//获取每一个字符串
            if (c >= 'a' && c <= 'z'){
                smallCount++;
            }else if(c >= 'A' && c <= 'Z'){
                bigCount++;
            }else if(c >= '0' && c <= '9'){
                numberCount++;
            }
        }
        System.out.println("大写字母:"+bigCount+"个");
        System.out.println("小写字母:"+smallCount+"个");
        System.out.println("数字:"+numberCount+"个");
    }
}

二、StringBuffer

1、概述

  • 用 String 拼接字符串,会产出一个新的字符串,又耗时又浪费空间,而 StringBuffer 可以解决这个问题
  • 特点:线程安全
  • buffer:原意是缓冲

2、StringBuffer 类的构造方法

  • capacity:容量
  • public StringBuffer()
  • public StringBuffer(int capacity)//指定容量的字符串缓冲区对象
  • public StringBuffer(String str)//指定字符串内容的字符串缓冲区对象
package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
       StringBuffer s1 = new StringBuffer();
        System.out.println(s1);
        System.out.println(s1.capacity());//指定容量的字符串缓冲区对象
        System.out.println(s1.length());

        StringBuffer s2 = new StringBuffer(50);
        System.out.println(s2);
        System.out.println(s2.capacity());
        System.out.println(s2.length());
        System.out.println("---------------------");

        StringBuffer s3 = new StringBuffer("让世界充满爱");
        System.out.println(s3);
        System.out.println(s3.capacity());
        System.out.println(s3.length());
    }
}

3、StringBuffer 类的成员方法

添加功能

  • public StringBuffer append(String str)
  • public StringBuffer insert(int offset,String str)
package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = s1.append("苍井空是娃娃脸");
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s1 == s2);
        System.out.println("-------------------");

        s1.append("吗??");
        s1.append("其实,");
        s1.append("不是的,");
        s1.append("因为她看起来年轻而已!!");
        System.out.println(s1);
        System.out.println("+++++++++++++++++++++");

        //还可以这样添加
        s1.append("相对于苍井空").append("来说,").append("我更喜欢波多野结衣一点");
        System.out.println(s1);
        System.out.println("_+_+_+_+_+_+_+_+_+_+_+_+_+_");

        StringBuffer s3 = s1.append(",真的啊!");
        System.out.println(s1 == s3);

        s1.insert(10,"love");
        System.out.println(s1);
    }
}

删除功能

  • public StringBuffer deleteCharAt(int index)
  • public StringBuffer delete(int start,int end)
package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
        StringBuffer s1 = new StringBuffer();
        s1.append("I").append("love").append("java");
        System.out.println(s1);

        //删除
        s1.delete(5,9);
        System.out.println(s1);
        System.out.println("-------------------------");

        s1.deleteCharAt(1);//删除一个字符
        System.out.println(s1);
    }
}

替换功能

  • public StringBuffer replace(int start,int end,String str)
package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
        StringBuffer s1 = new StringBuffer();
        s1.append("I").append("love").append("java");
        System.out.println(s1);

        //替换
        s1.replace(5,9,"php");
        System.out.println(s1);
    }
}

反转功能

  • public StringBuffer reverse()
package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
        StringBuffer s1 = new StringBuffer();
        s1.append("??吗我爱空井仓");
        System.out.println(s1);
        s1.reverse();
        System.out.println(s1);
    }
}

截取功能

  • public String substring(int start)
  • public String substring(int start,int end)
package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
        StringBuffer s1 = new StringBuffer();
        s1.append("苍井空好看吗??对我来说,并不好看!");
        System.out.println(s1);
        //截取
        String s2 = s1.substring(8);
        System.out.println(s2);
        String s3 = s1.substring(0,8);
        System.out.println(s3);
    }
}

三、StringBuilder

四、总结

1、三个类主要区别

  • 运算速度
  • 线程安全性

2、运算速度比较(通常情况下):

StringBuilder > StringBuffer > String

3、常用比较

  • String:适用于少量的字符串操作。
  • StringBuilder:适用于单线程下在字符串缓冲区进行大量操作。
  • StringBuffer:适用于多线程下在字符串缓冲区进行大量操作。

4、

  • String 是内容不可以变的,StringBuffer 和 StringBuilder 是内容可变的
  • StringBuffer 是同步的,数据安全,效率低
  • StringBuilder 是不同步的,数据不安全,效率高

5、StringBuffer 和数组的区别

  • 二者都可以看做是一个容器,装其他数据
  • StringBuffer 的数据最终是一个字符串数据,而数组可以放置多种数据(必须是同一种数据类型)

6、String 和 StringBuffer 作为参数传递

package zifuchuan;

public class StringBufferDm {
    public static void main(String[] args){
        String s1 = "hello";
        String s2 = "word";
        System.out.println(s1+"---"+s2);
        change(s1,s2);
        System.out.println(s1+"---"+s2);

        StringBuffer sb1 = new StringBuffer("hello");
        StringBuffer sb2 = new StringBuffer("world");
        System.out.println(sb1+"----"+sb2);
        change(sb1,sb2);
        System.out.println(sb1+"----"+sb2);
    }

    private static void change(StringBuffer sb1, StringBuffer sb2) {
        sb1 = sb2;
        sb2.append(sb1);
    }

    private static void change(String s1, String s2) {
        s1 =  s2;
        s2 = s1 + s2;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43860260/article/details/91350939