Java 字符串字符

2024-01-08 15:01 更新

Java數(shù)據(jù)類型教程 - Java字符串字符


索引字符

您可以使用charAt()方法從String對(duì)象中獲取特定索引處的字符。索引從零開始。

下面的代碼打印索引值和字符在“W3CSCHOOL.CN"字符串中的每個(gè)索引處:

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

    // Get the length of string
    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);
    }

  }
}

上面的代碼生成以下結(jié)果。

Snipaste_2024-01-08_15-01-10

測(cè)試字符串是否為空

測(cè)試String對(duì)象是否為空。空字符串的長(zhǎng)度為零。

有三種方法可以檢查空字符串:

  • isEmpty()方法。
  • equals()方法。
  • 獲取字符串的長(zhǎng)度,并檢查它是否為零。

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

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

  }
}

更改案例

要將字符串的內(nèi)容轉(zhuǎn)換為小寫和大寫,請(qǐng)分別使用toLowerCase()和toUpperCase()方法。

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)