[11]字符串的存儲
一.字符串的存儲
* 1.字符串緩衝區
字符串是常量, 不能被修改, 所以可以共享, 多個引用指向相同的字符串常量時, 其實引用的是同一個對象, 這個對象在緩衝區中
示例1:
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2);
結果爲: true
原理是: 使用雙引號形式的字符串常量時, 會先在緩衝區內查找, 如果沒有就創建, 如果有就直接引用.
這段代碼總共創建了幾個字符串對象: 第一句創建了一個, 第二句沒有創建.
示例2:
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s1 == s2);
結果爲: false
原理是: 雙引號常量是在緩衝區中, 構造函數創建的字符串不在緩衝區中.
這段代碼總共創建了幾個字符串對象: 第一句創建一個對象, 第二句創建一個對象.
* 2.字符串串聯
示例1:
String s1 = "abc";
String s2 = "a";
String s3 = "bc";
String s4 = s2 + s3;
System.out.println(s1 == s4);
結果爲: false
原理是: 字符串相加是通過StringBuffer類的append()和toString()實現的, 而toString()返回的字符串是通過構造函數創建的.
示例2:
String s1 = "abc";
String s2 = "a" + "bc";
結果爲: true
原理是: 兩個字符串常量相加, 在編譯的時候之間改爲一個字符串常量.
3.字符串類構造函數
使用平臺默認碼錶, 將字節數組轉爲字符串:String(byte[] bytes)
使用指定碼錶, 將字節數組轉爲字符串:String(byte[] bytes, String charsetName)
使用指定碼錶, 將字節數組中的一部分數據轉爲字符串:String(byte[] bytes, int offset, int length, String charsetName)
使用字符數組創建字符串:String(char[] value)
*** 4.字符串常用方法
查找指定位置上的字符: char charAt(int index)
查找指定字符第一次出現的位置:int indexOf(String str)
查找指定字符最後一次出現的位置: int lastIndexOf(String str)
替換字符串:String replace(CharSequence target, CharSequence replacement)
截取字符串的子串:String substring(int beginIndex, int endIndex)
分割字符串:String[] split(String regex)
判斷是否包含一個字符串:boolean contains(CharSequence s)
按字典順序比較兩個字符串:int compareTo(String anotherString)
獲取長度:int length()
去掉前後空白:String trim()
5.StringBuffer和StringBuilder的區別
StringBuffer是從JDK1.0就有的一個類, 可以對字符串進行追加, 插入, 反轉等操作, 線程安全同步的, 但是效率較低. 我們在單線程訪問的時候不需要同步.
在JDK5之後, 出現了StringBuilder類, 它的功能和StringBuffer相同, 但是沒有進行同步, 速度快, 淘汰了StringBuffer.
6.寫出下面代碼的運行結果
public class Foo {
public static void main(String[] args) {
String strValue = "ABCDEFG";
strValue.substring(3);// String類所有方法都不會改變原字符串的值
strValue.concat("123");
System.out.println(strValue);
String value = new String ("ABCDEFG");// ABCDEFG
System.out.println(strValue == value);// false
}
}