始める無料で始める

String の長さを調べよう

テキストは1文字のものから段落全体まで、さまざまな長さがあります。String に含まれる文字数を把握することは、入力の検証やテキストの整形・処理において欠かせません。Java で String の長さを測る方法を見ていきましょう!

この演習はコースの一部です

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);
    }
}
コードを編集して実行