ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[toc] ### 一、初识字符串 String是一个<b>类(class),不输入基本数据类型</b>,是一个引用类型。 ### 二、空字符串和null区别 ~~~ String s1="";//空字符串有引用,有地址 String s2=null;//null表示的是空的引用,不能使用 ~~~ 空字符串是有效的引用,有地址,只不过是内容的长度时0; null这个引用的空的引用,不能使用,使用一定会报空指针异常。 ### 三、字符串的获取常用方法 #### charAt ~~~ charAt(int index)    //返回指定索引处的char值 ~~~ #### indexOf ~~~ public int indexof(String ch,int fromIndex); //返回在此字符串中第一次出现字符ch的索引,从指定位置fromIndex开始搜索 ~~~ #### lastIndexOf ~~~ public int lastIndexOf(String ch); //返回指定字符在此字符串中最后一次出现处的索引。 ~~~ #### getBytes ~~~ String s = "abcde"; //获取这个字符串对应的字符的数组 byte[] bytes = s1.getBytes(); System.out.println(bytes); ~~~ #### toCharArray ~~~ s.toCharArray() //把字符串转换为数组 ~~~ #### substring ~~~ substring(int beginIndex)    //该子字符串从指定索引处的字符开始,直到此字符串末尾 substring(int beginIndex,int endIndex)    //该子字符串从指定的beginIndex开始,包头不包尾 ~~~ #### split ~~~ s.split(String regex) //根据给定的正则表达式来拆分此字符串;用String类型的数组来接收 ~~~ ### 练习案例 ~~~ //查找字符串中li个数 public class StringTest1 {    public static void main(String[] args) {        String s ="alksfdjasliasjdklasdfliakljdsfalsilizxliasdliasdf";        int index = s.indexOf("li");        int count = 0; //当indexOf匹配不到要找的字符串时会返回-1,这里就是利用这一点        while (index!=-1){           count++; //每次查找的起始点往后挪两位,是因为li长度为2           index=s.indexOf("li",index+2);       }        System.out.println(count);   } } ~~~ ![](https://img.kancloud.cn/2b/27/2b27ea0527b6ddd128641aa00054be6f_499x373.png) 分析:String类型的字符串不可变,你必须新new一个str才能变。substring无法改变str! 要达到效果得这样写: str=str.substring(2,6) //<b>substring包头不包尾</b> ![](https://img.kancloud.cn/da/16/da16621111bd5be83d3358d73646ba29_632x394.png) 分析:StringBuffer里面没有重写equals方法,故它会调用它的父类Object的equals方法,而<b>Object里的equals是比较地址!!</b>