Implementing String Algorithms
| English | Chinese | Pinyin |
|---|---|---|
| StringIndexOutOfBoundsException | 越界异常 | yuè jiè yì cháng |
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==.
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.
Looping over the characters of HELLO
A loop visits indices 0 to length()-1.
The correct loop condition to visit every character of String s is...
Valid indices are 0..length()-1, so i < s.length().
Accessing index s.length() of a String throws...
The last valid index is length()-1.
To build a reversed String, since Strings are immutable, you...
Strings are immutable — build a fresh one.
How many characters does a loop visit for the String "HELLO" (using i < length())?
Indices 0..4 → 5 characters.
The accumulator pattern from loops also applies to counting characters in a String.
count++ inside an index loop counts matching characters.