Java String類

字串在Java編程中廣泛使用,字串就是一系列字元(由一個個的字元組成)。 在Java編程語言中,字串被視為對象。

Java平臺提供String類來創建和操作字串。

1. 創建字串

創建字串的最直接方法是 -

String str = "Hello world!";

每當它在代碼中遇到字串文字時,編譯器就會創建一個String對象,在本例中str對象的值為Hello world!

與其他對象一樣,可以使用new關鍵字和構造函數來創建String對象。String類有11個構造函數,方便使用不同的源(例如:字元數組)提供字串的初始值。

示例

public class StringDemo {

   public static void main(String args[]) {
      char[] helloArray = { 'Y', 'i', 'i', 'b', 'a', 'i' };
      String helloString = new String(helloArray);
      System.out.println( helloString );
   }
}

執行上面示例代碼,得到下結果:

zaixian

注 - String類是不可變的,因此一旦創建,就無法更改String對象。 如果想要對字串進行大量修改,則應使用StringBuffer和StringBuilder

2. 字串長度

用於獲取對象資訊的方法稱為訪問器方法。 可以與字串一起使用來獲取字串長度的一個訪問器方法是length()方法,它返回字串對象中包含的字元數。

以下程式是String類的length()方法的示例。

public class StringDemo {

   public static void main(String args[]) {
      String greeting = "Hi,Welcome to xuhuhu.com";
      int len = greeting.length();
      System.out.println( greeting+" 字串的長度是: " + len );
   }
}

執行上面示例代碼,得到下結果:

Hi,Welcome to xuhuhu.com 字串的長度是: 24

3. 連接字串

String類包含一個用於連接兩個字串的方法 -

string1.concat(string2);

這將返回一個新字串:string1,並且string1在結尾處添加了string2。 還可以將concat()方法與字串文字一起使用,例如 -

"My name is ".concat("Maxsu");

字串通常使用+運算符連接,如 -

"Hello," + " world" + "!"

上面代碼執行後得到的結果是:

"Hello, world!"

下麵再來看另一個例子 -

public class StringDemo {

   public static void main(String args[]) {
      String string1 = "Bai";
      System.out.println("Yii" + string1 + ".com");
   }
}

上面代碼執行後得到的結果是:

xuhuhu.com

3. 創建格式化字串

Java中使用printf()format()方法來列印帶有格式化數字的輸出。 String類有一個等效的類方法format(),它返回一個String對象而不是一個PrintStream對象。

使用Stringstatic format()方法可以創建重用的格式化字串,而不是一次性列印語句。 例如 -

System.out.printf("The value of the float variable is " +
                  "%f, while the value of the integer " +
                  "variable is %d, and the string " +
                  "is %s", floatVar, intVar, stringVar);

上面列印語句可使用格式化寫為:

String fs;
fs = String.format("The value of the float variable is " +
                   "%f, while the value of the integer " +
                   "variable is %d, and the string " +
                   "is %s", floatVar, intVar, stringVar);
System.out.println(fs);

4. String類方法

以下是String類定義的方法列表 -

編號 方法 描述
1 char charAt(int index) 返回指定索引處的字元。
2 int compareTo(Object o) 將此String對象與另一個對象進行比較。
3 int compareTo(String anotherString) 按字典順序比較兩個字串。
4 int compareToIgnoreCase(String str) 按字典順序比較兩個字串,但不區分大小寫。
5 String concat(String str) 將指定的字串連接到此字串的末尾。
6 boolean contentEquals(StringBuffer sb) 當且僅當此String表示的字串與指定的StringBuffer相同的字元序列時,才返回true
7 static String copyValueOf(char[] data) 返回表示指定數組中字元序列的String對象形式。
8 static String copyValueOf(char[] data, int offset, int count) 返回表示指定數組中字元序列的String對象形式。
9 boolean endsWith(String suffix) 判斷此字串是否以指定的字元作為尾碼結尾。
10 boolean equals(Object anObject) 將此字串與指定的對象進行比較。
11 boolean equalsIgnoreCase(String anotherString) 將此String與另一個String進行比較,忽略大小寫。
12 byte getBytes() 使用平臺的默認字元集將此String編碼為位元組序列,將結果存儲到新的位元組數組中。
13 byte[] getBytes(String charsetName) 使用指定的字元集將此String編碼為位元組序列,將結果存儲到新的位元組數組中。
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 將此字串中的字元複製到目標字元數組中。
15 int hashCode() 返回此字串的哈希碼。
16 int indexOf(int ch) 返回指定字元在此字串中第一次出現的索引。
17 int indexOf(int ch, int fromIndex) 返回指定字元在此字串中第一次出現的索引,它從指定索引處開始搜索。
18 int indexOf(String str) 返回指定子字串在此字串中第一次出現的索引。
19 int indexOf(String str, int fromIndex) 從指定的索引處開始,返回指定子字串在此字串中第一次出現的索引。
20 String intern() 返回字串對象的規範表示。
21 int lastIndexOf(int ch) 返回指定字元在此字串中最後一次出現的索引。
22 int lastIndexOf(int ch, int fromIndex) 返回指定字元在此字串中最後一次出現的索引,它從指定的索引開始向後搜索。
23 int lastIndexOf(String str) 返回指定子字串在些字串中最後出現的索引。
24 int lastIndexOf(String str, int fromIndex) 返回指定子字串在此字串中最後一次出現的索引,它從指定索引開始向後搜索。
25 int length() 返回此字串的長度。
26 boolean matches(String regex) 判斷此字串是否與給定的正則運算式匹配。
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 判斷兩個字串區域是否相等。
28 boolean regionMatches(int toffset, String other, int ooffset, int len) 判斷兩個字串區域是否相等。
29 String replace(char oldChar, char newChar) 返回一個新字串,該字串是使用newChar替換此字串中出現的所有oldChar後的字串。
30 String replaceAll(String regex, String replacement) 將替換此字串中匹配給定正則運算式的每個子字串。
31 String replaceFirst(String regex, String replacement) 將替換此字串中第一個匹配給定正則運算式的子字串。
32 String[] split(String regex) 將此字串拆分為給定正則運算式的匹配項。
33 String[] split(String regex, int limit) 將此字串拆分為給定正則運算式的匹配項。
34 boolean startsWith(String prefix) 判斷此字串是否以指定的字串首碼開頭。
35 boolean startsWith(String prefix, int toffset) 判斷此字串在指定的索引是否以指定的首碼開始。
36 CharSequence subSequence(int beginIndex, int endIndex) 返回一個新的字元序列,它是該序列的子序列。
37 String substring(int beginIndex) 返回一個新字串,該字串是此字串的子字串。
38 String substring(int beginIndex, int endIndex) 返回一個新字串,該字串是此字串的子字串。
39 char[] toCharArray() 將此字串轉換為新的字元數組。
40 String toLowerCase() 使用默認語言環境的規則將此String中的所有字元轉換為小寫。
41 String toLowerCase(Locale locale) 使用給定Locale的規則將此String中的所有字元轉換為小寫。
42 String toString() 將這個對象(已經是一個字串)本身返回。
43 String toUpperCase() 使用默認語言環境的規則將此String中的所有字元轉換為大寫。
44 String toUpperCase(Locale locale) 使用給定Locale的規則將此String中的所有字元轉換為大寫。
45 String trim() 返回字串的副本,移除前導和尾隨空格。
46 static String valueOf(primitive data type x) 返回傳遞的數據類型參數的字串表示形式。

上一篇: Java Character類 下一篇: Java快速入門