Concepts / String Iteration and Indexing

String Iteration and Indexing

The parameters determine which string is searched and which character is treated as a match.

  • 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.

Definition

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

Key point

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.

Position 1bPosition 2aPosition 3nPosition 4aPosition 5nPosition 6anextnextnextnextnext
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.

Startcount = 0bcount = 0acount = 1ncount = 1acount = 2ncount = 2acount = 3Result3read nextread nextread nextread nextread nextread nextfinish
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.

Read characterMatches target?Increment countKeep countNext charactercomparetruefalsecontinuecontinue
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

  • Common mistake

    Initializing the counter inside the loop

    What it looks like
    for letter in text:
        count = 0
    Why it fails

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

    Do this instead

    Initialize the counter before the loop begins.

  • Common mistake

    Forgetting to increment the counter

    What it looks like
    if letter == target:
        pass
    Why it fails

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

    Do this instead

    Increment the counter inside the true branch of the condition.

  • Common mistake

    Using assignment instead of comparison

    What it looks like
    if letter = target:
    Why it fails

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

    Do this instead

    Use the comparison operator == for the match test.

  • Common mistake

    Placing the increment outside the condition

    What it looks like
    if letter == target:
        pass
    count = count + 1
    Why it fails

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

    Do this instead

    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.
Worked example

Tracing cocoa

Count the occurrences of o in cocoa.

  1. 1
    Initialize

    Set the counter to 0 before examining the string.

  2. 2
    Read c

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

  3. 3
    Read o

    o matches the target, so the counter becomes 1.

  4. 4
    Read c

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

  5. 5
    Read o

    o matches the target, so the counter becomes 2.

  6. 6
    Read a

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

Result

The final count is 2.

Pattern Summary

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

At a glance

  • 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.

Related concepts

More concepts starting with S