我们之前没少使用字符串String,今天我们来具体了解下,我们用文档查看,知道其在java.lang包里,所有""包裹字符串都默认是字符串实例
字符串特点
1被创建无法改变,2 可以共享使用(节省内存),3 字符串效果相当于char数组,但是底层是byte数组
字符串创建
常见3+1种方法,这里+1是直接赋值法,如String s = "abc";其他3为构造方法
1 String();创建空字符串
2 String(char[] arr); 创建基于char数组arr的字符串
3 String(byte[] arr); 创建基于byte数组arr的字符串

3+1代码如上
字符串常量池

我们使用如上代码创建1内容相同的字符串abc,分别查看其分别是否相等,可以看到赋值是相同的,但是都和数组创建不一样,这里只要是双引号包起来的就在常量池,对于基本类型是对数值的比较,而引用类型是对地址的比较

JDK1.7以后,常量池在堆中,如上图,创建str1,因为是双引号包裹,所以在常量池里创建一个String对象,里面的只存数组的地址,同时,字符串底层是用byte数组实现,就在堆内常量池外开辟了byte数组,并将地址给str1,同理str2会先到常量池去找,因为有创建好的,所以直接使用地址。而我们创建char数组,在堆内会转化成byte数组,而且newString对象只能在常量池外,所以str3的地址和str2,str1是不一样的
字符串方法
字符串的方法我们在api文档都可以找到,但是我们需要记住几种常用的方法
1 字符串比较
public boolean equals(object)

如上图,这个比较是字符串的内容比较,所以返回的是true。
注意,这里区分大小写,如果有大小写区别,返回false
a.equals(b)和b.equals(a)结果一样,具有对称性

虽然具有对称性,但是我们推荐常量写前面,因为字符串可以设为null(声明未赋值),这时,就会出现空指针异常
public boolean equalsIgnoreCase(object)

如字面所述,忽略大小写的比较
2 字符串获取方法
public int length() 返回字符串长度
public String concat(String s)将字符串和s拼接后返回新字符串(不影响原字符串)
public char charAt(int index) 返回index位置的字符
public int indexOf(String s)返回s在字符串的第一次出现的索引,不存在返回-1

代码如上
3 字符串截取
public String substring(int index); 返回子字符串切片,从index开始
public String substring(int begin,int end); 返回从begin到end-1索引的字符串切片

注意,这里不像python可以实现切片超出变成空字符串,而是会报错index超出范围,而且结果是生成了新的字符串
4字符串转换
public char[] toCharArray(); 将字符串的char数组返回,不改变原数组
public byte[] getBytes(); 将字符串的底层byte数组返回
public String replace(String old,String new);将字符串里old替换成new,不修改原始字符串,返回新字符串

5 字符串分割
public String[] split(String regex);将字符串按regex作为切割,返回String数组

一般的分割就不说了,这里说下点.比较特殊如上,需要加上2个\\转义才行,只写一个点表示匹配任何,其实函数参数就是正则表达式(regex),后续会学习
网友评论