• java字符串类的使用


    java字符串类的使用

    String

    • String是一个final类
    • 字符串是常量,使用双引号""
    • String对象的字符内容是存储在一个字符数组value[]中
    • String实现了Serializable接口,支持序列化
    • String实现了Comparable接口,可以比较大小

    通过字面量方式给字符串赋值,此时字符串声明在字符串常量池中,在字符串常量池中不允许存储相同内容的字符串。

    String不同实例化方法对比

    • String str = “hello” //字面量赋值
    • String s1 = new String(); //this.value = new char[0];
    • String s2 = new String(String original); //this.value = original.value;
    • String s3 = new String(char[] a); //this.value = Arrays.copyOf(value,value.lenth);
    • String s4 = new String(char[] a,int startIndex,int count);

    方法一:通过字面量方式,将字符串声明在字符串常量池中

    方式二:通过new + 构造器方式,保存的是地址值,是数据在堆空间中开辟空间以后对应地址值。

        public void test(){
            String s1 = "abc";
            String s2 = "abc";
            String s3 = new String("abc");
            String s4 = new String("abc");
            System.out.println(s1 == s2);//true
            System.out.println(s3 == s4);//flase
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    String s = new String(“abc”);方法创建对象,在内存中创建了几个对象?

    两个:一个是在堆空间中new,另一个是char[]对应的常量池数据:“abc”

    String不同拼接操作对比

    • 常量与常量的拼接结果在常量池中。
    • 只要有一个是变量,结果就在堆中。
    • 如果拼接结果调用intern()方法,返回值就在常量池中。
        public void test(){
            String s1 = "java";
            String s2 = "ee";
            String s3 = "javaee";
            String s4 = "java" + "ee";
            String s5 = s1 + "ee";
            String s6 = "java" + s2;
            String s7 = s1 + s2;
            String s8 = s5.intern();
            System.out.println(s3 == s4);//true
            System.out.println(s3 == s5);//false
            System.out.println(s3 == s6);//false
            System.out.println(s3 == s7);//false
            System.out.println(s3 == s8);//true
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    面试:判断输入结果

    public class test {
        String str = "good";
        public void change(String str){
            str = "test";
        }
        public static void main(String[] args) {
            test test = new test();
            test.change(test.str);
            System.out.println(test.str);//good
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    String常用方法

    • int length():返回字符串长度
    • char charAt(int index):返回索引处字符
    • boolean isEmpty():判断是否是空字符串
    • String toLowerCase():将String中字符转换为小写
    • String toUpperCase():将String中字符转换为大写
    • String trim():返回字符串副本,忽略开头末尾的空白
    • boolean equals(Object obj):比较字符串内容是否相同
    • boolean equalsIgnoreCase(String anotherString):忽略大小写,判断字符串内容是否相同
    • String concat(String str):将指定字符串连接到此字符串的结尾。同“+”
    • int compareTo(String str):比较两个字符串的大小
    • String substring(int beginIndex):返回新的字符串,从beginIndex处开始
    • String substring(int beginIndex,int endIndex):同上,从beginIndex开始,到endIndex结束
        public void test(){
            String s1 = "java";
            String s2 = " java ";
            String s3 = "JAVa";
            System.out.println(s1.length());//4
            System.out.println(s2.trim());//java
            System.out.println(s1.charAt(1));//a
            System.out.println(s3.toUpperCase());//JAVA
            System.out.println(s3.toLowerCase());//java
            System.out.println(s3.equals(s1));//false
            System.out.println(s3.equalsIgnoreCase(s1));//true
            System.out.println(s1.concat("ee"));//javaee
            System.out.println(s1.substring(2));//va
            System.out.println(s1.substring(2,3));//v
            System.out.println(s3.compareTo(s1));//-32
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • boolean endsWith(String sufflx):测试字符串是否以指定的后缀结束

    • boolean startsWith(String preflx):测试字符串是否以指定的前缀开始

    • boolean startsWith(String preflx,Int toffset):测试此字符串是否从指定索引开始的子字符串是否以指定前缀开始

    • boolean contains(CharSequence s):当且仅当此字符串包含指定char序列返回true

    • int lastIndexOf(String str):返回指定字符串在此字符串中最右边出现的索引

    • int lastIndexOf(String str,int fromIndex):返回指定子字符在此字符串中最后一次出现的索引,从指定索引开始反向查找

    • int indexOf(String str):返回指定字符串在此字符串中第一次出现的索引

    • int indexOf(String str,int fromIndex):返回指定子字符串在此字符串中第一次出现的索引,从指定索引开始。

      indexOf和lastIndexOf如果未找到都是返回-1

        public void test(){
            String s1 = "helloworld";
            System.out.println(s1.endsWith("d"));//true
            System.out.println(s1.endsWith("ld"));//true
            System.out.println(s1.startsWith("h"));//true
            System.out.println(s1.startsWith("e",1));//true
            System.out.println(s1.contains("world"));//true
            System.out.println(s1.lastIndexOf("o"));//6
            System.out.println(s1.lastIndexOf("o",5));//4
            System.out.println(s1.indexOf("o"));//4
            System.out.println(s1.indexOf("o",5));//6
            System.out.println(s1.indexOf("o",7));//-1
            System.out.println(s1.lastIndexOf("o",3));//-1
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • String replace(char oldChar,char newChar):返回一个新的字符串,使用newChar替换所有的oldChar
    • String replace(CharSequence target,CharSequence replacement):使用指定字面值替换所有匹配字面值的子字符串
    • String replaceAll(String regex,String replacement):使用给定的replacement替换字符串中所有匹配正则表达式的子字符串
    • String replaceFirst(String regex,String replacement):使用给定的replacement替换字符串中第一个匹配正则表达式的子字符串
    • boolean matches(String regex):判断字符串是否匹配给定的正则表达式
    • String[] split(String regex):根据给定的正则表达式的匹配拆分此字符串
    • String[] split(String regex,int limit):根据给定的正则表达式的匹配拆分此字符串,最多不超过limit个,如果超过,剩下的全部放到最后一个元素。

    String类型转换

    String与基本数据类型、包装类

    • String——》基本数据类型、包装类,调用包装类静态方法:parseXxx(str)
    • 基本数据类型、包装类——》String,调用String重载的valueOf(xxx)
        public void test(){
            String s1 = "123";
            int i = Integer.parseInt(s1);
            String s2 = String.valueOf(i);
            String s3 = i +"";
            
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    String与char[]

    • String —>char[]:调用String的toCharArray()
    • char[] ---->String:调用String的构造器
        public void test(){
            String s1 = "hello";
            char[] chars = s1.toCharArray();
            for (char c : chars) {
                System.out.println(c);
            }
            String s2 = new String(chars);
            System.out.println(s2);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    StringBuffer

    线程安全,效率低;底层使用可变的char[]

    底层数组大小默认16

    /** StringBuffer.java**/
    public StringBuffer() {
            super(16);
        }
    /**AbstractStringBuilder.java**/
    AbstractStringBuilder(int capacity) {
            value = new char[capacity];
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    length()返回依旧是添加的内容长度

        public void test(){
            StringBuffer stringBuffer = new StringBuffer();
            System.out.println(stringBuffer.length());//0
        }
    
    • 1
    • 2
    • 3
    • 4
        public synchronized int length() {
            return this.count;
        }
        
    
    • 1
    • 2
    • 3
    • 4

    如果添加的数据底层数组装不下,那就需要扩容底层数组,默认情况下,扩容为原来容量的2倍+2,同时将原有数组中的元素复制到新的数组中。

    常用方法

    • append(xxx):用于进行字符串拼接

    • delete(int start ,int end):删除指定位置的内容

    • replace(int start ,int end ,String str):把[start,end]位置替换为str

    • insert(int offset,xxx):在指定位置插入xxx

    • reverse():把当前字符序列逆转

        public void test(){
            StringBuffer stringBuffer = new StringBuffer("abcdef");
            stringBuffer.append("hello");
            System.out.println(stringBuffer);//abcdefhello
            stringBuffer.replace(0,2,"java");
            System.out.println(stringBuffer);//javacdefhello
            stringBuffer.insert(5,"hi");
            System.out.println(stringBuffer);//javachidefhello
            stringBuffer.delete(5,7);
            System.out.println(stringBuffer);//javacdefhello
            stringBuffer.replace(0,4,"ab");
            System.out.println(stringBuffer);//abcdefhello
            stringBuffer.reverse();
            System.out.println(stringBuffer);//ollehfedcba
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    StringBuilder

    线程不安全,效率高;底层使用可变的char[]

    常用方法

    同StringBuffer;

  • 相关阅读:
    软件流程和管理(七):个人、激励和团队
    linux添加普通用户并且只能访问指定目录
    Matlab学习-常用函数
    RocketMQ 5.0 POP消费模式
    从基础入门到学穿C++
    微信浏览器自动播放音频(兼容Android和iOS)
    <string.h>字符操作函数的实现(strcpy、strcat、mem)
    c++的引用和指针
    内置数据库H2和内置Redis(测试结果来啦)
    ssh终端工具推荐-WindTerm
  • 原文地址:https://blog.csdn.net/weixin_48747169/article/details/125620806