String tracer – indices, substrings and string algorithms
Computer ScienceAlgorithms & Problem SolvingAges 15–16
Loading…
Sign in to playA string is drawn as a row of character cells indexed from 0. String operations mode covers concatenation, length, character at an index, substring/slice [a, b) with the end index excluded, find (indexOf), equals, compareTo, upper/lower case, replace, split and character codes, with results side by side in pseudocode, Python and Java, including out-of-range errors. Loop algorithms mode steps through counting a character, reversing, a palindrome check and naive substring search with a trace table, and a final mode counts comparisons for naive search versus Boyer–Moore.
Lesson: Strings: indexing, slicing and substring, string methods and string traversal
What it shows
A string is an immutable sequence of characters, each with an index starting at 0. Python slices s[a:b] and Java's s.substring(a, b) include index a and exclude index b, so they return b − a characters; Java throws an exception when an index is out of range, while Python slicing clips the indices. Methods such as upper, replace and split return new strings. Loop algorithms visit the characters one index at a time, and a trace table records each step. Boyer–Moore searches by comparing the pattern from the right and skipping ahead after a mismatch.
How to use
Type a string s (and t, r or c when asked). In String operations, choose an Operation, drag a and b, and compare the results for Pseudocode, Python and Java; tick Show character codes to see ASCII/Unicode values. In Loop algorithms, pick an Algorithm and the Code language, then press Step or Play and follow the highlighted line and the trace table. In Naive vs Boyer–Moore, step both searches and compare their comparison counts.
Parameters you can change
- Mode String operations, Loop algorithms, Search: naive vs Boyer–Moore
- Operation s + t (concatenation), length, character at index a, substring / slice [a, b), find t (find / indexOf), equals, compare (compareTo), to upper case, to lower case, replace t with r, split at c, character code (ord / chr)
- Algorithm count a character c, reverse the string, palindrome check, naive substring search
- Code language Pseudocode, Python, Java
- String s
- Second string t (pattern)
- Replacement r
- Character c
- Index a 0–28
- Index b 0–28
- Show character codes
- Speed 0.5–10 steps/s
Questions to explore
- Why does s.substring(2, 5) return 3 characters, and what happens in Java and in Python if b is larger than the length?
- Why does "apple".compareTo("Apple") give a positive number?
- Why does Boyer–Moore need fewer comparisons than naive search when the pattern is long?