Topic 2.10 — Implementing String Algorithms

Goal: use loops + conditionals with String methods to implement common text algorithms (counting, searching, building new strings, and analyzing characters).

The big idea

A lot of “real” problems are really string problems: checking passwords, counting letters, finding words, or building a new string. In this topic, you’ll implement those using: loops + String methods + boolean tests.

String tools you’ll use a lot

Method What it returns Common use
s.length() int loop bounds
s.substring(a, b) String extract part of a string
s.indexOf(x) int search for a character/string
s.charAt(i) char look at one character
s.equals(t) boolean compare strings

(You won’t need every method in every question—learn the patterns.)

Pattern 1: Count something in a string

Example: count vowels by scanning characters.

int count = 0;
for (int i = 0; i < s.length(); i++) {
  char ch = s.charAt(i);
  if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
    count++;
  }
}

Pattern 2: Find whether something exists

Use a loop + boolean flag (or a loop condition).

boolean found = false;
int i = 0;

while (i < s.length() && !found) {
  if (s.charAt(i) == target) {
    found = true;
  }
  i++;
}

Pattern 3: Build a new string

Example: keep only letters that match a rule.

String result = "";
for (int i = 0; i < s.length(); i++) {
  char ch = s.charAt(i);
  if (ch != ' ') {
    result = result + ch;
  }
}

On AP CSA, simple concatenation like this is fine for small examples.

Pattern 4: Compare two strings (important)

Use equals, not ==, for content comparison.

if (a.equals(b)) {
  // same characters in the same order
}
// == checks if they are the same object reference (not what you want)
if (a == b) { ... }

Common mistakes

  • Loop bounds: using i <= s.length() causes StringIndexOutOfBoundsException.
  • Using == instead of equals to compare strings.
  • Forgetting that substring(a, b) stops before b.
// Correct bounds:
for (int i = 0; i < s.length(); i++) {
  char ch = s.charAt(i);
}

Exam mindset

  • When scanning, always use: for (int i=0; i<s.length(); i++).
  • Use charAt(i) to inspect one character.
  • Use equals for comparing string contents.
  • Trace carefully: strings are indexed starting at 0.

Quick self-check

  1. What does s.length() return?
  2. What’s the last valid index in a string of length n?
  3. Why is equals better than == for strings?
  4. What does substring(a, b) include/exclude?
  5. Write a loop that counts how many times 'x' appears in a string.

← Back to Unit 2 topics