Good catch.  Recursion or a while loop that modifies the string as you go are two strategies that would solve this.