Implementing String Algorithms · Implementando Algoritmos de String
| English | Português |
|---|---|
| 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.
Iterando sobre caracteres
- Para processar uma String, itere sobre seus índices de
0alength() - 1. for (int i = 0; i < s.length(); i++) { ... s.substring(i, i+1) ... }s.substring(i, i+1)dá o String de um caractere no índicei.- Isso visita cada caractere em ordem — a base da maioria dos algoritmos de String.
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==.
Contando caracteres
- Combine o loop com um
ifpara contar caracteres correspondentes. - "Conte as vogais": loop, e
ifo caractere atual é uma vogal,count++. - O padrão de acumulador de 2.9 aplica-se diretamente a Strings.
- Compare caracteres com
.equals(), não==.
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.
Construindo um novo String
- Para transformar texto, construa um novo String com
+, pois Strings são imutáveis. String result = "";thenresult = result + something;inside the loop.- "Reverter uma String": anexe cada caractere do final para o início.
- O original nunca muda — você acumula uma nova String.
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.
Limites de índice
- Índices válidos vão de
0alength() - 1; ir fora lança um StringIndexOutOfBoundsException 越界异常. s.substring(i, i+1)é seguro apenas enquantoi < s.length().- A condição do loop
i < s.length()mantémidentro do intervalo. - Erros de limite off-by-one são o bug mais comum em loops de String.
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.
Loop índices de String com i < s.length(), não i <= s.length(). O último índice válido é length() - 1; tocar no índice length() lança um StringIndexOutOfBoundsException. E construa texto transformado acumulando uma nova String (result += ch) — você não pode editar uma String in loco, pois Strings são imutáveis.
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".
Contando vogais em 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++; }- Visita cada caractere; conta se aparecer em
"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.
Processar uma String iterando seus índices de 0 a length()-1 (condição i < s.length()), lendo cada caractere com s.substring(i, i+1). Conte com um if, ou construa uma nova String acumulando com + (Strings são imutáveis). Permanecer dentro dos limites evita um StringIndexOutOfBoundsException.
Looping over the characters of HELLO · Iterando sobre os caracteres de HELLO
A loop visits indices 0 to length()-1. · Um laço visita índices de 0 até length()-1.
The correct loop condition to visit every character of String s is... · A condição correta de laço para visitar todos os caracteres da String s é...
Valid indices are 0..length()-1, so i < s.length(). · Índices válidos são 0..length()-1, então i < s.length().
Accessing index s.length() of a String throws... · Acessar o índice s.length() de uma String lança...
The last valid index is length()-1. · O último índice válido é length()-1.
To build a reversed String, since Strings are immutable, you... · Para construir uma String invertida, já que Strings são imutáveis, você...
Strings are immutable — build a fresh one. · Strings são imutáveis — construa uma nova.
How many characters does a loop visit for the String "HELLO" (using i < length())? · Quantos caracteres um laço visita para a String "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. · O padrão acumulador de laços também se aplica a contar caracteres em uma String.
count++ inside an index loop counts matching characters. · count++ dentro de um laço por índice conta caracteres correspondentes.