Concepts / String Iteration and Indexing

String Iteration and Indexing

The counter pattern is a fundamental computational technique: initialize a counter to 0, loop through data, check a condition, and increment the counter when the condition is true.

  • Programming

A Count That Changes Selectively

Suppose you want to find how many times the letter a appears in banana. The important idea is not simply to increase a number repeatedly. Instead, the number increases only when the character currently being examined satisfies a condition. This selective updating is the counter pattern.

The counter pattern initializes a counter to 0, loops through data, checks a condition, and increments the counter when the condition is true.

A counter represents the number of matching events found so far. It changes on a successful match and remains unchanged when the condition is false.

Mapping Positions to Characters

When a loop examines banana, it visits each character in sequence: b, a, n, a, n, a. At every step, the program has a current character and can compare it with the target character a. The loop does not increment the counter merely because it moved to the next character; it increments only when the current character matches the target.

nextnextnextnextnextPosition 1bPosition 2aPosition 3nPosition 4aPosition 5nPosition 6a
Which character is examined at each position as the loop moves through the string?

The position map shows why the loop must inspect every character. The target appears three times, but those matches are separated by nonmatching characters. A correct counter must preserve its current value during the nonmatching iterations and then increase when the next a is encountered.

Tracing the Counter

What do you think happens?

Before reading the trace, predict the counter value after each character in banana is examined while counting a.

  • 0, 1, 1, 2, 2, 3
  • 1, 2, 3, 4, 5, 6
  • 0, 0, 1, 1, 2, 2
Reveal answer

Answer: 0, 1, 1, 2, 2, 3

The counter starts at 0. It stays unchanged for b and n, and increases by 1 for each of the three a characters.

read nextread nextread nextread nextread nextread nextfinishStartcount = 0bcount = 0acount = 1ncount = 1acount = 2ncount = 2acount = 3Result3
How does the counter change after each character is examined, including iterations where the character does not match?

The trace has two kinds of steps. When the current character is b or n, the comparison is false and count keeps its previous value. When the current character is a, the comparison is true and count increases by exactly 1. After all six characters have been examined, count is 3.

The Counting Process

A character-counting loop follows four actions in order: create the counter with value 0, read each character, test whether it equals the target, and increment the counter only after a successful comparison. The condition controls the state change. Without the condition, every character would be counted rather than only matching characters.

comparetruefalsecontinuecontinueRead characterMatches target?Increment countKeep countNext character
What happens after a character is read, and how does the condition determine whether the counter is incremented?
python
Output
3

The increment is indented inside the condition, so it runs only for a matching character. In this example, the three a characters trigger the increment, producing the final count 3.

Reusable Character Counting

Once the loop works, the same counter pattern can be placed inside a function. The function accepts the string to search and the character to count as parameters. This separates the counting process from one particular string or target, so the same logic can be reused with different inputs.

python
Output
3
2

The function keeps the same four-part process: initialize, iterate, test, and increment. The parameters determine which string is searched and which character is treated as a match. The return statement makes the accumulated count available to the caller.

Mistakes That Break the Count

  • Initializing the counter inside the loop

    The counter is reset during the iteration instead of accumulating across the characters.

    Fix: Initialize the counter before the loop begins.

  • Forgetting to increment the counter

    A matching character is recognized, but the accumulated total never changes.

    Fix: Increment the counter inside the true branch of the condition.

  • Using assignment instead of comparison

    The condition needs to compare the current character with the target character.

    Fix: Use the comparison operator == for the match test.

  • Placing the increment outside the condition

    The counter increases for every loop iteration, including characters that do not match.

    Fix: Place the increment in the conditional block so only matches increase the total.

Practice the Trace

EASY

Trace the counter pattern for the string "cocoa" when the target character is "o". Write the counter value after each character is examined, then state the final count.

Hints
  • Start the counter at 0.
  • Keep the counter unchanged when the current character is not o.
  • Increase it by 1 for each matching o.

Tracing cocoa

Count the occurrences of o in cocoa.

Initialize: Set the counter to 0 before examining the string.

Read c: c does not match o, so the counter remains 0.

Read o: o matches the target, so the counter becomes 1.

Read c: c does not match o, so the counter remains 1.

Read o: o matches the target, so the counter becomes 2.

Read a: a does not match o, so the counter remains 2.

The final count is 2.

Pattern Summary

  1. The counter pattern starts at 0, examines each item, checks a condition, and increments only when the condition is true.
  2. String character counting uses iteration to visit each character and comparison to identify matches.
  3. The counter remains unchanged during nonmatching iterations and accumulates the total number of matches.
  4. A function with string and target-character parameters turns one counting loop into a reusable tool.
  5. The same pattern can support other tasks that accumulate results based on a condition.

Key Takeaways

  • The counter pattern combines initialization, iteration, condition checking, and selective incrementing.
  • To count a character, inspect every character and increment only when it matches the target.
  • Tracing unchanged and changed counter values reveals how the final total is accumulated.
  • A function can generalize the pattern by accepting the string and target character as parameters.