[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);
? }
}
~~~

分析:String類型的字符串不可變,你必須新new一個str才能變。substring無法改變str!
要達到效果得這樣寫:
str=str.substring(2,6) //<b>substring包頭不包尾</b>

分析:StringBuffer里面沒有重寫equals方法,故它會調用它的父類Object的equals方法,而<b>Object里的equals是比較地址!!</b>