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 );
   }
}

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

Yiibai

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

2. 字符串長度

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

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

public class StringDemo {

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

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

Hi,Welcome to Yiibai.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");
   }
}

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

YiiBai.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)

返回傳遞的數據類型參數的字符串表示形式。