AP Computer Science A · Study guide

String Selection and Iteration Algorithms

AP® Computer Science A · Selection and Iteration

Standard String Algorithms

Loops that work through a string one character or one substring at a time: finding substrings with a property, counting substrings that meet a criterion, building reversed and filtered strings, and getting the loop bounds exactly right.

Big Picture

Strings are sequences of characters with indices from 0 to length() - 1, so a loop can visit them one position at a time. There are standard string algorithms to find if one or more substrings have a particular property, to determine the number of substrings that meet specific criteria, and to create a new string with the characters reversed. Each combines a loop over indices, the substring method to extract pieces, and selection or concatenation to test or build. Because strings are immutable, every "change" builds a new string.

1Visiting Each Character

The foundation of every string algorithm is a loop over the indices: for (int i = 0; i < word.length(); i++). Inside it, word.substring(i, i + 1) produces the single character at index i as a String, which can be compared with equals, searched with indexOf, or joined to another string.

The bound i < word.length() is exactly right for single characters: the last index is length() - 1, and substring(length() - 1, length()) is the last character. For the empty string the loop runs zero times, which is usually correct, since there are no characters to examine.

Storing the extracted character in a well-named variable, such as String letter = word.substring(i, i + 1);, makes the rest of the loop body easier to read and avoids repeating the substring call in every test. The variable is declared inside the loop because it is needed only for the current pass.

GoalLoop boundsKey operation
Examine each characterfor (int i = 0; i < s.length(); i++)s.substring(i, i + 1)
Examine substrings of length kfor (int i = 0; i <= s.length() - k; i++)s.substring(i, i + k)
Compare neighborsfor (int i = 0; i < s.length() - 1; i++)s.substring(i, i + 1) vs s.substring(i + 1, i + 2)
Visit from the endfor (int i = s.length() - 1; i >= 0; i--)Append each character
Worked Example 1 Counting a character

How Many Times Does a Letter Appear?

Count the letter "s" in "mississippi".

Code
String word = "mississippi";
int count = 0;
for (int i = 0; i < word.length(); i++)
{
    if (word.substring(i, i + 1).equals("s"))
    {
        count++;
    }
}
System.out.println(count);
Output
4
  1. 1Visit every index from 0 to length() - 1.
  2. 2Extract one character as a string with substring(i, i + 1), and compare it with equals.
  3. 3Count matches: indices 2, 3, 5, 6.
Result: The output is 4. Looping over indices and testing substring(i, i + 1) is the basic pattern for examining each character.

2Counting Characters With a Property

Counting combines the character loop with the frequency pattern: a counter starts at 0, and an if inside the loop increases it when the current character satisfies a test. The test can compare with a specific character, check a range, or test membership in a set of characters.

A convenient membership test uses indexOf: a string such as "aeiou" serves as the set, and "aeiou".indexOf(letter) returns −1 exactly when letter is not in it. This replaces a long condition like letter.equals("a") || letter.equals("e") || ... with one clear expression.

Figure 1. A string of allowed characters works as a set: indexOf returns −1 exactly when a character is not in it.
Worked Example 2 Characters with a property

Counting Vowels

Count the vowels in "education".

Code
String word = "education";
String vowels = "aeiou";
int count = 0;
for (int i = 0; i < word.length(); i++)
{
    String letter = word.substring(i, i + 1);
    if (vowels.indexOf(letter) >= 0)
    {
        count++;
    }
}
System.out.println(count);
Output
5
  1. 1The property test. vowels.indexOf(letter) is −1 for consonants and 0 to 4 for vowels (Figure 1).
  2. 2The vowels in "education": e, u, a, i, o.
Result: The output is 5. Testing membership with indexOf against a string of allowed characters avoids a long chain of || comparisons.
Common Mistake 1 · Comparing Single Characters With ==

word.substring(i, i + 1) == "s" compares references, and a substring is a new object, so the result is false even when the character is "s". Use equals.

3Substrings of Any Length

To count or find a longer pattern, slide a window of the pattern's length across the string. With k = pattern.length(), each pass examines word.substring(i, i + k) and compares it with the pattern. Every possible starting position is checked, so overlapping occurrences are all counted: "aa" appears three times in "aaaa."

The starting index must stop at word.length() - k, because a window starting later would need characters past the end. The loop condition is therefore i <= word.length() - k, or equivalently i < word.length() - k + 1. If the pattern is longer than the word, the condition is false at the start and the loop correctly finds nothing.

Figure 2. To examine every substring of a given length, a loop moves the starting index from 0 to length() - k, taking substring(i, i + k) each time.
Worked Example 3 Counting substrings

Occurrences of a Two-Letter Pattern

Count how many times "an" appears in "banana" and "ss" appears in "mississippi".

Code
public static int countPattern(String word, String pattern)
{
    int k = pattern.length();
    int count = 0;
    for (int i = 0; i <= word.length() - k; i++)
    {
        if (word.substring(i, i + k).equals(pattern))
        {
            count++;
        }
    }
    return count;
}
Output
2
2
3
  1. 1Window length k. Each pass examines substring(i, i + k).
  2. 2Bounds. The last valid start is word.length() - k, so the condition is i <= word.length() - k (Figure 4).
  3. 3Overlaps count. In "aaaa", windows at 0, 1, and 2 all equal "aa": 3.
Result: The output is 2, 2, 3. Sliding a window of the pattern's length across the string determines the number of substrings that meet a criterion.
Common Mistake 2 · Using the Character Bound for a Longer Window

With i < word.length() and substring(i, i + 2), the final pass asks for an ending index one past the end and throws a StringIndexOutOfBoundsException. Reduce the bound by the window length minus 1.

4Finding Whether a Substring Has a Property

Sometimes the question is not "how many" but "is there any," and often "where." The loop examines substrings in order and stops as soon as one qualifies, reporting its starting index, or −1 if none does. Stopping early is done through the loop condition: a variable such as found starts at −1, the condition includes found == -1, and the body records the index when it finds a match.

Properties can involve more than one character. Comparing each character with its neighbor finds double letters; comparing a substring with a pattern finds a word; testing whether every character passes a check can be done by searching for the first character that fails and reporting whether none was found. Returning a Boolean or an index lets the caller decide what to do with the answer.

Worked Example 4 Finding a property

Is There a Double Letter?

Find whether a word contains two identical letters in a row, and where the first pair starts.

Code
public static int firstDouble(String word)
{
    int found = -1;
    int i = 0;
    while (found == -1 && i < word.length() - 1)
    {
        if (word.substring(i, i + 1).equals(word.substring(i + 1, i + 2)))
        {
            found = i;
        }
        i++;
    }
    return found;
}
Output
1
-1
  1. 1Compare neighbors. Each pass compares the character at i with the one at i + 1, so i stops at length() - 2.
  2. 2Stop at the first match. The loop condition includes found == -1, so the search ends as soon as a pair is found.
  3. 3"bookkeeper": "oo" starts at 1. "planet": no pair, so −1.
Result: The output is 1 and −1. Finding whether any substring has a property usually returns a position, or −1 when no substring qualifies, mirroring indexOf.
Standard algorithmResult typeExample
Find if one or more substrings have a propertyboolean or an index (−1 if none)First double letter in "bookkeeper": 1
Count substrings meeting a criterionint"an" in "banana": 2
Create a new string with the characters reversedString"stressed" → "desserts"

5Building New Strings

Because strings are immutable, algorithms that "change" a string actually build a new one, usually starting from the empty string "" and concatenating pieces in a loop. Adding each character to the end of the result copies the string; adding each character to the front reverses it. Looping from the last index down to 0 while appending also reverses.

Adding selection inside the loop filters the characters: append only those that pass a test, such as consonants or digits, and the result contains just those characters in their original order. Reversal combined with equals answers questions about the whole string, such as whether a word is a palindrome.

Figure 3. Visiting the characters from left to right and adding each one to the front of the result creates a new string with the characters reversed.
iword.substring(i, i + 1)reversed after the pass
0"s""s"
1"t""ts"
2"r""rts"
3"e""erts"
………
7"d""desserts"
Worked Example 5 Reversal

Creating a Reversed String

Reverse "stressed".

Code
String word = "stressed";
String reversed = "";
for (int i = 0; i < word.length(); i++)
{
    reversed = word.substring(i, i + 1) + reversed;
}
System.out.println(reversed);
Output
desserts
  1. 1Add to the front. Each character goes before everything collected so far, so the first character ends up last.
  2. 2A new string. word is unchanged; reversed refers to a new string each pass.
Result: The output is desserts. Placing each character in front of the result builds a new string with the characters reversed. (Looping from the last index down to 0 and appending works too.)
Worked Example 6 Using reversal

Palindromes

A palindrome reads the same in both directions. Test three words.

Code
public static boolean isPalindrome(String word)
{
    String reversed = "";
    for (int i = word.length() - 1; i >= 0; i--)
    {
        reversed = reversed + word.substring(i, i + 1);
    }
    return reversed.equals(word);
}
Output
true
true
false
  1. 1Reverse by counting down. The loop visits indices from length() - 1 to 0 and appends each character.
  2. 2Compare with equals. A word is a palindrome when its reversal has the same characters.
Result: The output is true, true, false. Combining the reversal algorithm with equals tests a property of the whole string.
Worked Example 7 Building a filtered string

Removing the Vowels

Create a new string containing only the consonants of "programming".

Code
String word = "programming";
String result = "";
for (int i = 0; i < word.length(); i++)
{
    String letter = word.substring(i, i + 1);
    if ("aeiou".indexOf(letter) == -1)
    {
        result = result + letter;
    }
}
System.out.println(result);
Output
prgrmmng
  1. 1Selection inside the loop decides which characters to keep.
  2. 2Appending keeps the kept characters in their original order.
Result: The output is prgrmmng. Combining a character test with concatenation creates a new string built from selected characters.
Common Mistake 3 · Expecting the Original String to Change

Reversing or filtering produces a new string in another variable; the original is untouched. If the result is never stored, or the original variable is printed instead, the work is lost. Print or return the variable that holds the newly built string.

6Getting the Bounds Right

Most errors in string algorithms are off by one errors in the loop bounds, and they show up as a StringIndexOutOfBoundsException at run time. The rule is simple: for a window of length k, valid starting indices run from 0 to length() - k. Single characters use k = 1, neighbor comparisons use k = 2, and patterns use their own length.

Before running a string loop, check the last pass by hand: what is i, and what ending index does substring receive? If that ending index is greater than length(), the bound is one too large. Testing with very short strings, including strings shorter than the pattern and the empty string, catches the remaining edge cases.

Figure 4. For substrings of length k, the starting index can go up to length() - k. Going further throws a StringIndexOutOfBoundsException.
Worked Example 8 Off by one

A Window That Runs Past the End

Why does this loop fail, and how is it fixed?

Code that fails at run time
String word = "level";
for (int i = 0; i < word.length(); i++)
{
    System.out.println(word.substring(i, i + 2));
}
  1. 1The windows "le", "ev", "ve", "el" print for i = 0 to 3.
  2. 2At i = 4, substring(4, 6) asks for an ending index of 6 in a string of length 5, which throws a StringIndexOutOfBoundsException.
  3. 3Fix. For windows of length 2, use i < word.length() - 1.
Result: The program prints four substrings and then stops with an exception. The loop bound must account for the window length: the last start is length() - k.
Common Mistake 4 · Stopping One Pass Too Early

The opposite error, i < word.length() - k without the equals sign, skips the last window. It does not crash, so it is easy to miss: counting "na" in "banana" with this bound finds 1 instead of 2. Check the final window explicitly.

Four Habits for String Algorithms

1. substring(i, i + 1)

Extract one character as a String; compare with equals.

2. Last Start = length() − k

Bound every window by its length.

3. Build From ""

Append to copy or filter; prepend to reverse.

4. −1 for Not Found

Report a position, or −1 when nothing qualifies.

Core Synthesis

There are standard string algorithms to find if one or more substrings have a particular property, to determine the number of substrings that meet specific criteria, and to create a new string with the characters reversed. Each loops over valid starting indices, uses substring to extract a character or a longer substring, and either tests it with equals or indexOf or joins it into a new string. For substrings of length k, the starting index runs from 0 to length() - k; going further results in a StringIndexOutOfBoundsException.