Реализация алгоритмов строк
Введено| English | Значение |
|---|---|
| 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.
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==.

Reversing a string by walking its indexes backwards
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.
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.
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.
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".
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.
Обход символов строки HELLO
Цикл посещает индексы от 0 до length()-1.
Правильное условие цикла для посещения каждого символа строки s — это...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Действительные индексы находятся в диапазоне 0..length()-1, поэтому используется i < s.length().
Обращение к индексу s.length() строки вызывает исключение...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Последний действительный индекс равен length()-1.
Чтобы построить реверсированную строку, учитывая неизменность String, вы...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
строки неизменяемы — создавайте новую.
Сколько символов посетит цикл для строки "HELLO" (при использовании условия i < length())?
Сложность 2/5 · 140 монет + небольшой бонус за первое выполнение сегодня
Индексы 0..4 → 5 символов.
Шаблон аккумуляторного суммирования из циклов также применяется для подсчета символов в строке.
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
count++ внутри индексного цикла подсчитывает совпадающие символы.