in reply to Can we "grow" a string?

Let's see:

Are your specifications really that general? Or are you trying to solve a more restricted problem? My suspicion is the latter, given that you have a precise size for the string. You can write such general solutions if you really need them, but is that really what you need? Maybe it would be worth your effort to narrow things down a bit?

General solutions always take more time to implement than specific solutions. And they don't always save programming time for their users either. They just change what you program. The more general the solution, the more like a framework. The more like a framework, the more configuration data you need to plan and set-up to use. It will also be a lot harder to document and test. More abtraction means more explanation. It also means that code coverage alone may not be enough to test it. You also have to consider all possible inputs and consequent paths through the code.

If you really do need a general purpose expand-in-place algorithm, you might want to consider using something similar to attributed strings:

  1. Break the string up into an array of subsequences. Both the expandable substrings and non-expandable substrings should get their own subsequence.
    • the non-expandable sub-sequences can be represented by the substring itself.
    • the expandable sub-sequences can be represented by an object. This object has one field (the substring), and one method (an algorithm to check its size and expand it). Substrings with different expansion algorithms can be assigned different object classes. Or if you don't like creating all of those classes, just add another field to your object. This extra field stores a code reference to your expansion algorithm. Your expansion method simply passes the string to this code reference and resets the substring field with the result.
  2. Pass the array of subsequences to a function that calls the expansion method on each object and reassembles the string by concatenating all of the expanded sub-sequences in order.

Best, beth