開始使用免費開始

String 有多長?

文字有各種長度——從單一字元到整段段落。知道一個字串包含多少字元,對於驗證、格式化與處理文字都很重要。來看看 Java 如何幫你量出字串的長度吧!

本練習屬於課程

Java 入門

檢視課程

練習說明

  • 使用 .length() 方法取得變數 bookName 的長度,並將結果存成 bookNameLength
  • 取得作者名稱 "Terry Pratchett" 的長度,並用正確的基本型別儲存。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

class HowLong {
    public static void main(String[] args) {
    
        String bookName = "Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch";
        
        // Find the length of bookName
        int bookNameLength = bookName.____();
        
        // Find the length of the String and save it
        ____ authorNameLength = "Terry Pratchett".____;
        
        System.out.println("The length of the book title is " + bookNameLength);
        System.out.println("The length of the author's name is " + authorNameLength);
    }
}
編輯並執行程式碼