A String traversal is a loop that visits a string's characters by index, from 0 to length() - 1, using substring to pick out each piece. With it you can count a letter or a substring, build a new string such as a reversal, and find where text occurs. The one rule that keeps it safe: a substring that starts at i and has n characters must end at or before length(), so i stops at length() - n.
Quick check
What does "planet".substring(2, 3) return?Show answerHide answer
"a", the single character at index 2.
substring(2, 3)starts at index 2 and stops before index 3.A string has length 6. What is its last valid index?Show answerHide answer
5, one less than the length, because indexes start at 0.
How many substrings of length 2 does "frog" have, starting at each possible index?Show answerHide answer
3: "fr", "ro" and "og", starting at indexes 0, 1 and 2. A start at index 3 would need index 4, which does not exist.
Know these already? Jump to the practice questions
What you'll be able to do
- Determine what a traversal loop counts, builds or returns for a given string.
- Choose loop bounds so every
substringcall stays inside the string. - Explain how a reversal or a filtered copy is built one piece at a time.
- Identify the header or statement that makes a traversal miss a position or throw an exception.
Key terms
Traversal
A loop that visits every position of a string (or other collection) in order, by index.
- In plain English
- Walking through a string one character at a time.
- Don't write
- "A traversal changes the string as it goes."
Loop bound
The value in a loop's condition that decides the last index the loop visits.
- In plain English
- Where the loop stops.
- Don't write
- "The bound is always
s.length()."
How do you visit every character of a String?
Use an index loop from 0 while i < s.length(), and take the one-character string at index i with s.substring(i, i + 1). On the last pass i is s.length() - 1, so i + 1 equals the length, which substring allows.
String s = "banana";
int count = 0;
for (int i = 0; i < s.length(); i++)
{
if (s.substring(i, i + 1).equals("a"))
{
count++;
}
}
The "a"s sit at indexes 1, 3 and 5, so count ends at 3. Compare with equals, never ==: == tests whether two references point to the same object, not whether the characters match. length, substring and equals are on the Java Quick Reference.
Check yourself
Show answerHide answer
4 times, at indexes 2, 3, 5 and 6.
How do you check every substring of length n?
Take s.substring(i, i + n) at each start i. The last start that fits is s.length() - n, so the condition is i <= s.length() - n.
String s = "banana";
int count = 0;
for (int i = 0; i <= s.length() - 2; i++)
{
if (s.substring(i, i + 2).equals("an"))
{
count++;
}
}
i runs from 0 to 4, giving "ba", "an", "na", "an", "na", so count ends at 2. With i < s.length() instead, the pass at i = 5 calls substring(5, 7) and throws a StringIndexOutOfBoundsException. Overlapping matches are all counted: "banana" holds "ana" twice, starting at 1 and at 3.
Key idea
For substrings of length n, the loop runs while i <= s.length() - n.
Check yourself
Show answerHide answer
4: starts 0, 1, 2 and 3, because the length is 6 and 6 − 3 = 3.
How do you build a new string?
Start with the empty string "" and join pieces onto it inside the loop. A String is immutable, so each + makes a new string, and you must assign it back. To drop characters, add only the ones that pass a test:
String s = "to be or";
String t = "";
for (int i = 0; i < s.length(); i++)
{
String ch = s.substring(i, i + 1);
if (!ch.equals(" "))
{
t += ch;
}
}
t ends as "tobeor". Where you join decides the order: t = t + ch adds to the end and copies the order; t = ch + t adds to the front and reverses it.
Check yourself
Show answerHide answer
"god". Each character is added to the front, so the last one ends up first.
How do you find where a substring occurs?
For the first occurrence, return i at the first match and return -1 after the loop if nothing matched. That is what indexOf, on the Java Quick Reference, already does. For the last occurrence, keep looping and overwrite a position variable on every match. In "boot room" the first "o" is at index 1 and the last is at index 7.
Check yourself
Show answerHide answer
-1, because "z" never appears.
Worked example 1: Reverse a string
Question: What is printed when this code segment runs?
String s = "stop";
String rev = "";
for (int i = s.length() - 1; i >= 0; i--)
{
rev += s.substring(i, i + 1);
}
System.out.println(rev);
What tells you the method
A loop that counts down and builds a string: trace i and rev pass by pass.
Step 1: Find the start.
s.length()is 4, soistarts at 3, the last index, and the loop runs for 3, 2, 1, 0.WhyStarting at
s.length()would callsubstring(4, 5)and throw an exception.Step 2: Trace each pass.
iPiece rev3 "p" "p" 2 "o" "po" 1 "t" "pot" 0 "s" "pots" Why+=adds each piece to the end, and the pieces arrive last character first.
Check it
rev has 4 characters, the same as s, and its first character is the last character of "stop".
Answer
pots
Worked example 2: Count a two-letter substring
Question: What is printed when this code segment runs?
String s = "cookbook";
int count = 0;
for (int i = 0; i <= s.length() - 2; i++)
{
if (s.substring(i, i + 2).equals("oo"))
{
count++;
}
}
System.out.println(count);
What tells you the method
A fixed-length substring compared at each start: list the starts, then test each piece.
Step 1: Find the starts.
s.length()is 8, soiruns from 0 to 6.WhyThe condition
i <= 8 - 2allowsiup to 6, andsubstring(6, 8)still fits.Step 2: Test each piece.
The pieces are "co", "oo", "ok", "kb", "bo", "oo", "ok". Only the ones at 1 and 5 equal "oo", so
countends at 2.Whyequalscompares the characters exactly.
Check it
The last piece, at i = 6, is "ok", which ends at index 7, the last index of "cookbook", so no position was missed.
Answer
2
Worked example 3: Choose the loop header
Question: The method should return how many times "the" appears in s.
public static int countThe(String s)
{
int count = 0;
/* missing loop header */
{
if (s.substring(i, i + 3).equals("the"))
{
count++;
}
}
return count;
}
Which header can replace /* missing loop header */?
- A)
for (int i = 0; i < s.length(); i++) - B)
for (int i = 0; i < s.length() - 3; i++) - C)
for (int i = 1; i <= s.length() - 3; i++) - D)
for (int i = 0; i <= s.length() - 3; i++)
What tells you the method
A loop-bound question: test the first and last positions, where off-by-one errors show.
Step 1: Test a match at the end.
In "bathe", "the" starts at index 2, which is
s.length() - 3. B stops at 1 and returns 0; D reaches 2 and returns 1.WhyThe last valid start is
s.length() - 3, so<misses it.Step 2: Test a match at the start and the upper limit.
In "then", C starts at 1 and misses index 0. A reaches
i= 2 in "then" and callssubstring(2, 5), which throws an exception.WhyIndex 0 is a valid start, and no start past
s.length() - 3fits.
Check it
D on "theme of the" (length 12) checks starts 0 to 9 and finds matches at 0 and 9, returning 2.
Answer
D
Your turn
Question: What is printed when this code segment runs?
String s = "abcdefg";
String t = "";
for (int i = 0; i < s.length(); i += 2)
{
t += s.substring(i, i + 1);
}
System.out.println(t);
Step 1: List the values of
i.igoes up by 2: 0, 2, 4, 6. At 8 the condition8 < 7fails.Step 2: Your go: find each piece and build
t.
Show the full solutionHide the solution
Step 2. The pieces at indexes 0, 2, 4 and 6 are "a", "c", "e" and "g", added to the end in that order, so t is "aceg". The last call, substring(6, 7), ends exactly at the length, so it is allowed.
Answer: aceg
Traps
Trap
Every traversal can use i < s.length() as its condition.
It seems right because that bound visits every index. But a call such as s.substring(i, i + 2) reaches past the end on the last pass and throws an exception; for pieces of length n, stop at s.length() - n.
s has length 5. What is the last safe value of i for s.substring(i, i + 2)?
3, because substring(3, 5) ends exactly at the length.
Trap
s.substring(i, i + 1) == "a" tests whether the character is "a".
It seems right because == works for int values. But substring returns a new String object, so == compares references and can be false even when the characters match. Use equals.
Which test is reliable: piece == "a" or piece.equals("a")?
piece.equals("a").
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), multiple-choice questions ask what a traversal prints or returns, or which loop header or statement completes it. In free response you may traverse a string in a method you write, so check the first pass, the last pass and the bound every time.
Practice questions
- Recall Which expression gives the one-character String at index
iofs, whereiis a valid index?
- A)
s.substring(i, i + 1) - B)
s.substring(i) - C)
s.substring(i, i) - D)
s.substring(i - 1, i)
Show answer
Answer: A. It starts at index i and stops before i + 1, so it holds exactly one character.
Why the others are wrong:
- B runs from index
ito the end of the string. - C has equal indexes, so it returns the empty string.
- D counts positions from 1, giving the character before index
i.
- Apply What is printed when this code segment runs?
String s = "excellence";
int count = 0;
for (int i = 0; i < s.length(); i++)
{
if (s.substring(i, i + 1).equals("e"))
{
count++;
}
}
System.out.println(count);
Show answer
Answer: 4
Marking points:
- "e" is at indexes 0, 3, 6 and 9.
- Apply What value does
poshold after this code segment runs?
String s = "to do or not";
int pos = -1;
for (int i = 0; i < s.length(); i++)
{
if (s.substring(i, i + 1).equals("o"))
{
pos = i;
}
}
Show answer
Answer: 10
Marking points:
- "o" is at indexes 1, 4, 6 and 10; each match overwrites
pos, so the last one stays.
- Exam-style The method should return how many times a character equals the one right after it, so
countDoubles("book")should return 1. It throws an exception instead.
1: public static int countDoubles(String s)
2: {
3: int count = 0;
4: for (int i = 0; i < s.length(); i++)
5: {
6: String a = s.substring(i, i + 1);
7: String b = s.substring(i + 1, i + 2);
8: if (a.equals(b))
9: {
10: count++;
11: }
12: }
13: return count;
14: }
Which change makes the method work as intended?
- A) Change line 4 to
for (int i = 1; i < s.length(); i++) - B) Change line 4 to
for (int i = 0; i < s.length() - 1; i++) - C) Change line 4 to
for (int i = 0; i <= s.length(); i++) - D) Change line 7 to
String b = s.substring(i, i + 2);
Show answer
Answer: B. Line 7 reads index i + 1, so i must stop at s.length() - 2; then "book" gives 1.
Why the others are wrong:
- A still reaches the last index, so line 7 still reaches past the end.
- C goes one step further past the end.
- D compares one character with two, and on the last pass it still reaches past the end.
- Apply What is printed when this code segment runs?
String s = "planet";
String t = "";
for (int i = s.length() - 1; i >= 0; i -= 2)
{
t += s.substring(i, i + 1);
}
System.out.println(t);
Show answer
Answer: tnl
Marking points:
itakes 5, 3, 1; the characters there are "t", "n" and "l".
- Exam-style
revstarts as"". Which statement, as the body offor (int i = 0; i < s.length(); i++), leavesrevholdingsreversed?
- A)
rev = rev + s.substring(i, i + 1); - B)
rev = s.substring(i) + rev; - C)
rev = s.substring(i, i + 1) + rev; - D)
rev = s.substring(i + 1, i + 2) + rev;
Show answer
Answer: C. Each character goes on the front, so "abc" builds "a", "ba", "cba".
Why the others are wrong:
- A adds to the end, so it copies
sin its original order. - B adds the whole rest of the string each time: "abc" gives "cbcabc".
- D is one index ahead, so it skips the first character and reaches past the end on the last pass.
- Recall A string has length 9. You check every substring of length 4. What is the largest starting index the loop should use?
Show answer
Answer: 5
Marking points:
- The last start is the length minus the piece length: 9 − 4 = 5, and
substring(5, 9)ends exactly at the length.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- One character:
s.substring(i, i + 1), withifrom 0 tos.length() - 1. - Pieces of length
n: startiruns whilei <= s.length() - n. - Compare pieces with
equals, never==. - Build strings from
"": join at the end to copy the order, at the front to reverse it. - First match: return at once, -1 if none. Last match: overwrite a position on every match.