Implementing String Algorithms · Implementación de Algoritmos de Cadenas
| English | Español |
|---|---|
| StringIndexOutOfBoundsException/strɪŋ ˈɪndeks ˈaʊtəv baʊndz ekˈsepʃn/ | StringIndexOutOfBoundsException |
Looping over characters
- To process a String, loop over its indices from
0tolength() - 1. for (int i = 0; i < s.length(); i++) { ... s.substring(i, i+1) ... }s.substring(i, i+1)gives the one-character String at indexi.- This visits every character in order — the basis of most String algorithms.
Iterar sobre caracteres
- Para procesar un String, itere sobre sus índices desde
0hastalength() - 1. for (int i = 0; i < s.length(); i++) { ... s.substring(i, i+1) ... }s.substring(i, i+1)devuelve el String de un solo carácter en el índicei.- Esto recorre cada carácter en orden — la base de la mayoría de los algoritmos de Strings.
Counting characters
- Combine the loop with an
ifto count matching characters. - "Count the vowels": loop, and
ifthe current character is a vowel,count++. - The accumulator pattern from 2.9 applies directly to Strings.
- Compare characters with
.equals(), not==.
Contar caracteres
- Combine el bucle con un
ifpara contar coincidences. - "Contar las vocales": itere y
ifel carácter actual es una vocal,count++. - El patrón del acumulador de 2.9 se aplica directamente a los Strings.
- Compare caracteres con
.equals(), no con==.
Building a new String
- To transform text, build up a new String with
+, since Strings are immutable. String result = "";thenresult = result + something;inside the loop.- "Reverse a String": append each character from the end toward the start.
- The original never changes — you accumulate a fresh String.
Construir un nuevo String
- Para transformar texto, construya un nuevo String con
+, ya que los Strings son inmutables. String result = "";luegoresult = result + something;dentro del bucle.- "Invertir un String": apende cada carácter desde el final hacia el principio.
- El original nunca cambia — acumula un String fresco.
Index bounds
- Valid indices run
0tolength() - 1; going outside throws a StringIndexOutOfBoundsException 越界异常. s.substring(i, i+1)is safe only whilei < s.length().- The loop condition
i < s.length()keepsiin range. - Off-by-one bounds are the most common String-loop bug.
Límites de índice
- Los índices válidos van de
0alength() - 1; excederlos lanza una StringIndexOutOfBoundsException. s.substring(i, i+1)es seguro solo mientrasi < s.length().- La condición del bucle
i < s.length()mantieneidentro del rango. - Los errores de límite off-by-one son el error más común en bucles de Strings.
Loop String indices with i < s.length(), not i <= s.length(). The last valid index is length() - 1; touching index length() throws a StringIndexOutOfBoundsException. And build transformed text by accumulating a new String (result += ch) — you can't edit a String in place, because Strings are immutable.
Itere los índices del String con i < s.length(), no con i <= s.length(). El último índice válido es length() - 1; tocar el índice length() lanza una StringIndexOutOfBoundsException. Y construya texto transformado acumulando un nuevo String (result += ch) — no puede editar un String in situ, porque los Strings son inmutables.
Counting vowels in s:
int count = 0;for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i+1); if ("aeiou".indexOf(ch) >= 0) count++; }- Visits each character; counts it if it appears in
"aeiou".
Contar vocales en s:
int count = 0;for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i+1); if ("aeiou".indexOf(ch) >= 0) count++; }- Recorre cada carácter; lo cuenta si aparece en
"aeiou".
Process a String by looping its indices 0 to length()-1 (condition i < s.length()), reading each character with s.substring(i, i+1). Count with an if, or build a new String by accumulating with + (Strings are immutable). Staying in bounds avoids a StringIndexOutOfBoundsException.
Procesar una Cadena mediante el bucle de sus índices 0 a length()-1 (condición i < s.length()), leyendo cada carácter con s.substring(i, i+1). Contar con un if, o construir una nueva Cadena acumulando con + (las Cadenas son inmutables). Permanecer dentro de los límites evita una StringIndexOutOfBoundsException.
Looping over the characters of HELLO · Recorriendo los caracteres de HELLO
A loop visits indices 0 to length()-1. · Un bucle visita índices de 0 a length()-1.
The correct loop condition to visit every character of String s is... · La condición correcta del bucle para visitar cada carácter de la cadena s es...
Valid indices are 0..length()-1, so i < s.length(). · Los índices válidos son 0..length()-1, por lo tanto i < s.length().
Accessing index s.length() of a String throws... · Acceder al índice s.length() de una cadena provoca...
The last valid index is length()-1. · El último índice válido es length()-1.
To build a reversed String, since Strings are immutable, you... · Para construir una cadena invertida, dado que las cadenas son inmutables, usted...
Strings are immutable — build a fresh one. · Las cadenas son inmutables: construya una nueva.
How many characters does a loop visit for the String "HELLO" (using i < length())? · ¿Cuántos caracteres visita un bucle para la cadena "HELLO" (usando i < length())?
Indices 0..4 → 5 characters. · Índices 0..4 → 5 caracteres.
The accumulator pattern from loops also applies to counting characters in a String. · El patrón acumulador de los bucles también se aplica al contar caracteres en una cadena.
count++ inside an index loop counts matching characters. · count++ dentro de un bucle de índices cuenta los caracteres coincidentes.