字符串
字符串是字符的序列。Java語言在包java.lang中封裝了類的String和StringBuffer,分別用於處理不變字符串和可變字符串。兩者均被說明爲final,意味兩者均不含子類。
1. String類
Java中將字符串作爲String類型對象來處理。被創建的字符串是不能改變的。當需要改變字符串時,應創建一個新的String對象來保存新的內容,原字符串不變。
一個字符串對象一旦被配置,它的內容就是固定不變。
String str = "Hello";
str = "Good";
在這個程序片段中有兩個字符串對象,一個是Hello字符串對象,長度爲5;一個是Good字符串對象,長度爲4.兩個是不同的字符串對象。這段程序不是在Hello字符串後加上Good字符串,而是讓str名稱引用至Good字符串對象。在Java中,使用“=”將一個字符串對象指定給一個變量名稱,其意義爲改變該名稱所引用的對象。原來被引用的對象若無其他名稱來引用它,就會在適當的時候被Java的“垃圾回收”機制回收。
- String對象的創建
1)String(),默認構造方法,無參數。
String s1 = new String();
2)String(char chars[]),傳入字符數組。
char[] myChars={'a','b','c'};
String s2 = new String(myChars) //使用字符串“abc”初始化s2
3)String(char chars[],int startIndex,int numChars),傳入一個字符數組,從指定下標位置開始獲取制定個數的字符,用這些字符來初始化字符串變量。
char[] myChars={'h','e','l','l','o'};
String s3 = new String(myChars,1,3) //使用字符串“ell”初始化s3
4)String(String strObj),傳入另一個字符串對象,用該字符串對象的內容初始化。
String s4 = new String(s3); //這時s4也是“ell”
5)String(byte asciiChars[])
String(byte asciiChars[],int startIndex,int numChars)
實例:
public class Example {
public static void main(String[] args) {
byte ascii[] = {65,66,67,68,69,70};
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii,2,3);
System.out.println(s2);
}
}
運行結果:
- String的對象連接
1)使用符號“+”把兩個字符串連接起來。
String s1 = "Hello";
String s2 = "World";
String S = s1 + s2;
上面的代碼將字符串S賦值爲“HelloWorld”,注意單詞之間沒有空格。
2)當連接一個字符串和一個非字符串時,後者將被轉化爲字符串。
int age = 13;
String rating =“PG” + age;
將把rating的值賦爲字符串“PG13”。
這種特性常被用在輸出語句中,如:
System.out.println(“The answer is” + answer);
- String對象的編輯
方法 | 說明 |
---|---|
length() | 取得字符串的字符長度 |
equals() | 判斷原字符串中的字符是否等於指定字符串中的字符 |
toLowerCase() | 轉換字符串的英文字符爲小寫 |
toUpperCase() | 轉換字符串的英文字符爲大寫 |
public class Example {
public static void main(String[] args) {
String text = "hello";
System.out.println("字符串內容:"+text);
System.out.println("字符串長度:"+text.length());
System.out.println("是否等於hello:" +text.equals("hello"));
System.out.println("轉爲大寫:" +text.toUpperCase());
System.out.println("轉爲小寫:" +text.toLowerCase());
}
}
運行結果:
- String對象的訪問
方法 | 說明 |
---|---|
char charAt(int index) | 返回指定索引處的字符 |
int indexOf(int ch) | 返回指定字符第一個找到的索引位置 |
int indexOf(String str) | 返回指定字符串第一個找到的索引位置 |
int lastIndexOf(int ch) | 返回指定字符串最後一個找到的索引位置 |
String substring(int beginIdex) | 取出指定索引處至字符串尾端的子字符串 |
String substring(int beginIndex,int endIndex) | 取出指定索引範圍子字符串 |
char[] toCharArray() | 將字符轉換爲字符數組 |
- 判斷String對象是否相等
1)equals方法(實體)
測試兩個字符串是否相等。如果字符串p和t相等,p.equals(t)的返回值爲true,否則返回值爲false。
注意:p和t可以是字符串常量,也可以是字符串變量。
"Hello".equals(t); //合法
"HELLO"equalsIgnoreCase("hello"); //返回值爲true,判斷兩個字符串除大小寫區別外是否相等。
2)==
“==”判斷兩個引用變量是否指向同一引用。
public class Example {
public static void main(String[] args) {
String s1 = "hello";
String s2 = new String("hello");
String s3 = "hello";
String s4 = new String("hello");
System.out.println(s1 == s3); //字符串常量引用同一常量池的對象
System.out.println(s2 == s4); //字符串對象將分別創建
System.out.println(s1.equals(s2));
System.out.println(s3.equals(s4));
}
}
運行結果:
2.StringBuffer類
StringBuffer類表示了可變長度的可寫的字符序列。對於StringBuffer類對象,不僅能夠進行查找和比較操作,還可以進行添加、插入、修改之類的操作。每個StringBuffer對象都有一個容量,只要其字符序列的長度不超過其容量,就無需分配新的內部緩衝數組,如果內部緩衝數組溢出,StringBuffer對象的容量自動增大。
- 構造方法
public stringBuffer(): 默認構造方法。
public StringBuffer(int length):按照length作爲初始容量初始化StringBuffer對象。
public StringBuffer(String Str):按照String對象str爲StringBuffer對象初始字符串。
- 主要成員方法
public int length():得到當前StringBuffer的**長度**(字符數)。
public int capacity():得到當前StringBuffer的**容量**。
public synchronized void ensureCapacity(int minCapacity):確保StringBuffer的容量不小於minCapacity。
public synchronized void setLength(int newLength):確保StringBuffer的長度爲newLength。
public synchronized char charAt(int index):得到指定位置index的字符。
public synchronized void getChars(int srcBegin,int srcEnd,char dst[],int dstBegin):將StringBuffer中從srcBegin到srcEnd的字符拷貝到數組dst[] (開始位置爲dstBegin)。
3.String類與StringBuffer類的比較
- 相同點
① 都用來處理字符串;
②都提供了length()、toString()、charAt()和subString()方法,它們的用法在兩個類中相同;
③字符在字符串中的索引位置都從0開始。
- 不同點
①String類是不可變類,而StringBuffer類是可變類。String類的subString()、concat()、toLowerCase()、toUpperCase()和trim()等方法都不會改變字符串本身,而是創建並返回一個包含改變後內容的新字符串對象。StringBuffer的append()、replaceAll()、replaceFirst()、insert()和setCharAt()等方法都會改變字符緩衝區中的字符串內容。
②String類覆蓋了Object類的equals()方法,而StringBuffer類沒有覆蓋。
③ 兩個類都覆蓋了Object類的toString()方法,但各自實現方是不同,String類中的toString()方法返回了當前String實例本身的引用,StringBuffer類的toString()方法返回一個以當前StringBuffer的緩衝區中的所有字符爲內容的心String對象的引用。
④ String類對象可用操作符“+”進行連接,而StringBuffer類對象之間不行。