TryBugHunt
rustInfinite loopEasy

Digit counter hangs on text with letters

BugFind the bug and fix the code

What it should do

count_digits(text) returns how many characters in the text are digits 0 to 9. Example: count_digits("a1b2") → 2

What happens instead

count_digits("a1b2") never returns. The run is stopped by the time limit. count_digits("123") works and returns 3.

fn count_digits(text: &str) -> i32 {
    let chars: Vec<char> = text.chars().collect();
    let mut count = 0;
    let mut i = 0;
    while i < chars.len() {
        if !chars[i].is_ascii_digit() {
            continue;
        }
        count += 1;
        i += 1;
    }
    count
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

An easy Rust debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: continue jumps straight back to the while condition and skips the rest of the loop body, including i += 1. On the first letter, i stays the same, the same letter is checked again, and the loop runs forever. Text with only digits never reaches continue, so it seems to work.

The fix: Move i forward before continue, or use a for loop over text.chars() so the step cannot be skipped.

Remember: in a while loop, every path through the body must change the loop variable. A continue that comes before the step is a classic way to freeze a program.

The pattern behind it: infinite loops.

More infinite loops to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/2e7cd3a4-e586-4b8b-9d8e-d3501987e362" title="Debugging challenge: Digit counter hangs on text with letters" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/2e7cd3a4-e586-4b8b-9d8e-d3501987e362">TryBugHunt</a></p>