Strings and nested loops · Cadenas y bucles anidados
Strings and nested loops
- A
Stringis a row of characters, each with a position (an index). - The first index is
0, and the last islength() - 1. - In this lesson you walk through a String one character at a time, and put loops inside loops.
Cadenas y bucles anidados
- Un
Stringes una fila de caracteres, cada uno con una posición (un índice). - El primer índice es
0, y el último eslength() - 1. - En esta lección recorrerás un String carácter por carácter, e incluirás bucles dentro de bucles.
Traversing a String
s.length()gives the number of characters.s.charAt(i)gives the character at indexi.- Loop
ifrom0up tolength() - 1to visit every character.
Recorriendo un String
s.length()devuelve el número de caracteres.s.charAt(i)devuelve el carácter en el índicei.- Bucle
idesde0hastalength() - 1para visitar cada carácter.
public class Main {
public static void main(String[] args) {
String s = "code";
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
}
}
Counting characters
- You can count how many times a character appears.
- Use a counter that starts at
0. - A single character uses single quotes, like
'o'. Compare with==(chars, not Strings).
Contando caracteres
- Puedes contar cuántas veces aparece un carácter.
- Usa un contador que comience en
0. - Un solo carácter se encierra entre comillas simples, como
'o'. Comparar con==(chars, no Strings).
public class Main {
public static void main(String[] args) {
String s = "balloon";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'o') {
count++;
}
}
System.out.println(count); // 2
}
}
Building a new String
- Start with an empty String
""and add characters with+. - Reading from the end to the start reverses the String.
- Each
+makes a longer String.
Construyendo un nuevo String
- Comienza con un String vacío
""y añade caracteres con+. - Leer del final al inicio invierte el String.
- Cada
+produce un String más largo.
public class Main {
public static void main(String[] args) {
String s = "code";
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result = result + s.charAt(i);
}
System.out.println(result); // edoc
}
}
Enhanced for (preview)
- For walking a String you usually need the index, so a normal
foris best. - But Java also has an enhanced for loop that visits items directly.
- You will use it a lot with arrays in lesson 8. Here is a small preview with text.
Enhanced for (vista previa)
- Para recorrer un String usualmente necesitas el índice, por lo que un normal
fores lo mejor. - Pero Java también tiene un bucle enhanced for que visita los elementos directamente.
- Lo usarás mucho con arrays en la lección 8. Aquí hay una pequeña vista previa con texto.
public class Main {
public static void main(String[] args) {
String[] words = {"hi", "there", "!"};
for (String word : words) {
System.out.println(word);
}
}
}
Nested loops
- A nested loop is a loop inside another loop.
- The inner loop runs all the way for each step of the outer loop.
- Below, the outer loop picks a row, and the inner loop prints stars in that row.
Buces anidados
- Un bucle anidado es un bucle dentro de otro bucle.
- El bucle interno se ejecuta completamente para cada paso del bucle externo.
- A continuación, el bucle externo selecciona una fila, y el bucle interno imprime estrellas en esa fila.
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
String line = "";
for (int col = 1; col <= row; col++) {
line = line + "*";
}
System.out.println(line);
}
}
}
Common mistakes
- Strings are immutable — store the result of
s.substring(...)etc. s.length()is a method (with()), unlike an array's.length.
Errores comunes
- Los Strings son inmutables — guarda el resultado de
s.substring(...)etc. s.length()es un método (con()), a diferencia del.lengthde un array.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Ahora practica
- Cada tarea prellena la estructura de la clase — escribe tu código dentro de main, o completa el método mostrado.
- Presiona Run para compilar y ejecutar, luego Check answer.
- Tu código se compila y ejecuta en el servidor, así que incluso la primera ejecución es rápida.
Indexing a String · Indexación de una Cadena
Each char has an index from 0; substring takes a range. · Cada carácter tiene un índice que comienza en 0; substring toma un rango.
Complete countChar(String s, char c) so it returns how many times c appears in s. Use charAt and · y ==. For example countChar("balloon", 'o') is 2. · Completa countChar(String s, char c) para que devuelva cuántas veces aparece c en s. Usa charAt y ==. Por ejemplo, countChar("balloon", 'o') es 2.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete reverse(String s) so it returns s with the letters in the opposite order. For example reverse("code") is "edoc". Build a new String with +. · Completa reverse(String s) para que devuelva s con las letras en orden inverso. Por ejemplo, reverse("code") es "edoc". Construye una nueva String usando +.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use nested loops · bucles anidados to print a triangle of stars: line 1 has one *, line 2 has two, line 3 has three, line 4 has four. Print each line with System.out.println. · Usa bucles anidados para imprimir un triángulo de asteriscos: la línea 1 tiene un *, la línea 2 tiene dos, la línea 3 tiene tres, la línea 4 tiene cuatro. Imprime cada línea con System.out.println.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.