基础复习—String

String类的常用方法及刷题中遇到的问题

1、String常量对象与引用对象

**1.1 String是一个final类,代表不可变的字符序列
一个字符串对象一旦被配置,则内容不可变

String源码:

    @Stable
    private final byte[] value;

1.2 String的内存解析
String的底层使用char[]实现,char[]初始化时需要给定数组长度,初始化之后长度不可变

String s1="Hello";//常量池
        String s2="Hello";//常量池
        String s3=new String("Hello");//对象实体在堆,引用变量在栈

        System.out.println(s1==s2);//true
        System.out.println(s1==s3);//false
        System.out.println(s1.equals(s3));//true

        String s4="World";
        String s5=s1+s4;
        String s6=s1+"World";
        System.out.println(s5==s6);//false
        System.out.println(s5.equals(s6));//true

s1、s2和s3很容易理解,常量池和堆的不同,这与String的构造器有关
s5和s6地址不同:
s6:String的底层是通过char[]进行存储,因此s1(常量池)+字符串(char[]),需要重新初始化一个较长的char[],来放入最新字符串,因此常量池中重新创建了一个“HelloWorld”的常量,并将地址赋给s6
s5:因为java不能得到变量地址,考虑到String的构造方法,个人理解是s5=new String(“Hello”)+new String(“World”),因为s1和s4均为常量池中常量,因此最终s5是一个堆空间中的实例化对象

1.3 刷题时不使用编辑器总是用反的两个方法indexOf()、charAt()

        String s1="Hello";

        System.out.println(s1.indexOf("e"));//1
        System.out.println(s1.charAt(4));//o

1.4 split()方法
根据特定的字符,将字符串分割为字符串数组
java中方法:

public String[] split(String regex, int limit)

regex:字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符
limit定义了分割后的数组的最大长度
正则表达式比较复杂,学习了一会儿发现只是大致理解,远达不到能够用自己的语言在博客记录的水平,因此只针对这个String方法进行相关学习
字符串也可以看作是正则表达式,用于匹配该字符串对应的字符串

String s="Hello abc world abc hello";
        String[] s1=s.split("abc");
        for(String a:s1){
            System.out.println("---"+a+"---");
        }
        System.out.println(s1.length);

在这里插入图片描述

其余常用的字符中,一些字符如“ ”,可以直接作为参数对字符串进行分割:

 String s="Hello abc world abc hello   ";
        String[] s1=s.split(" ");
        for(String a:s1){
            System.out.println("---"+a+"---");
        }
        System.out.println(s1.length);

在这里插入图片描述
而另外一些转义字符需要加上“\”(不是”//“,注意),才能作为识别该字符进行分割,如“.”,如果仅使用“.”作为参数,在正则表达式中却代表另一种意思(看了半天看不太懂),因此“\.”才能作为参数,与之相似的还有”/“、”|“、”+“、”?“等,本地IDE编辑时,如果使用String.split("+"),IDE会报错,但是”|“则不会,上次机试就是吃了这个亏,切记!

错误:

String s="Hello|abc|world|abc|hello";
        String[] s1=s.split("|");
        for(String a:s1){
            System.out.print(a+"---");
        }
        System.out.println();
        System.out.println(s1.length);

在这里插入图片描述
正确:

String s="Hello|abc|world|abc|hello";
        String[] s1=s.split("\\|");
        for(String a:s1){
            System.out.print(a+"---");
        }
        System.out.println();
        System.out.println(s1.length);

在这里插入图片描述
1.5 String构造方法

public class test {
    public static void main(String[] args) {
        char[] c=new char[]{'a','b','c','d'};
        String s1=new String(c,0,2);//c可以是char[]、int[]、Byte[]
        System.out.println(s1);
    }
}

在这里插入图片描述


版权声明:本文为weixin_42182892原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。