¿Cuál es la longitud de un String?
El texto puede tener muchos tamaños: desde caracteres sueltos hasta párrafos completos. Saber cuántos caracteres contiene un String es clave para validar, formatear y procesar texto. ¡Vamos a ver cómo te ayuda Java a medir Strings!
Este ejercicio forma parte del curso
Introducción a Java
Instrucciones del ejercicio
- Usa el método
.length()para averiguar la longitud de la variablebookName, guardando el resultado comobookNameLength. - Calcula la longitud del nombre del autor,
"Terry Pratchett", y guárdala usando el tipo primitivo correcto.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
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);
}
}