CommencerCommencer gratuitement

Quelle est la longueur d'une chaîne ?

String est un ensemble de caractères et, souvent, vous devrez déterminer sa longueur. Au lieu de compter, il existe la méthode .length() !

Cet exercice fait partie du cours

Introduction à Java

Afficher le cours

Instructions

  • Utilisez la méthode .length() pour déterminer la longueur de la variable bookName, en enregistrant le résultat sous bookNameLength.
  • Veuillez déterminer la longueur du nom de l'auteur, "Terry Pratchett", et l'enregistrer en utilisant le type primitif approprié.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

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);
    }
}
Modifier et exécuter le code