Quanto è lunga una String?
Il testo può avere tutte le dimensioni: da singoli caratteri a interi paragrafi. Sapere quanti caratteri contiene una String è fondamentale per la convalida, la formattazione e l'elaborazione del testo. Vediamo come Java ti aiuta a misurare le String!
Questo esercizio fa parte del corso
Introduzione a Java
Istruzioni dell'esercizio
- Usa il metodo
.length()per trovare la lunghezza della variabilebookName, salvando il risultato comebookNameLength. - Trova la lunghezza del nome dell'autore,
"Terry Pratchett", e salvala usando il tipo primitivo corretto.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
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);
}
}