Java字串字元


字元所在的索引

可以使用charAt()方法從String物件中獲取指定索引處的字元。索引值是從零開始的。以下程式碼在「TW511.COM」字串中列印索引值和每個索引處對應的字元:

public class Main {
  public static void main(String[] args) {
    String str = "TW511.COM";

    // Get the length of string TW511.COM
    int len = str.length();

    // Loop through all characters and print their indexes
    for (int i = 0; i < len; i++) {
      System.out.println(str.charAt(i) + "  has  index   " + i);
    }

  }
}

上面的程式碼生成以下結果。

Y  has  index   0
I  has  index   1
I  has  index   2
B  has  index   3
A  has  index   4
I  has  index   5
.  has  index   6
C  has  index   7
O  has  index   8
M  has  index   9

測試字串是否為空

測試String物件是否為空,空字串的長度為零。有三種方法可以檢查空字串:

  • isEmpty() 方法.
  • equals() 方法.
  • 獲取字串的長度,並檢查它是否為零。

以下程式碼顯示如何使用三種方法:

public class Main {
  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "";
    // Using the isEmpty() method
    boolean empty1 = str1.isEmpty(); // Assigns false to empty1
    boolean empty2 = str2.isEmpty(); // Assigns true to empty1

    // Using the equals() method
    boolean empty3 = "".equals(str1); // Assigns false to empty3
    boolean empty4 = "".equals(str2); // Assigns true to empty4

    // Comparing length of the string with 0
    boolean empty5 = str1.length() == 0; // Assigns false to empty5
    boolean empty6 = str2.length() == 0; // Assigns true to empty6

  }
}

更改字元的大小寫

要將字串的內容轉換為小寫和大寫,請分別使用toLowerCase()toUpperCase()方法。

String str1 = new String("Hello"); // str1  contains "Hello" 
String str2 = str1.toUpperCase();   // str2 contains "HELLO" 
String str3 = str1.toLowerCase();   // str3 contains "hello"