Replace $number with $number+1 in std::string I want to detect $number substring in std::string and then replace it with $number + 1.

For example, the string Hello$9World$1 should become Hello$10World$2.

Here's my code:

#include &lt;iostream&gt;
#include &lt;string&gt;

void modifyDollarNumber(std::string &amp;str)
{
    for (size_t i = str.length(); i --&gt; 0 ;)
    {
        if (str[i] == '$')
        {
            size_t j = i + 1;
            while (j &lt; str.length() &amp;&amp; isdigit(str[j]))
            {
                ++j;
            }
            size_t len = j - (i + 1);
            if (len)
            {
                std::string sub = str.substr(i + 1, len);
                int num = std::stoi(sub) + 1;
                str.erase(i + 1, len);
                sub = std::to_string(num);
                str.insert(i + 1, sub);
            }
        }
    }
}

int main()
{
    std::string str = "!$@#$34$1%^&amp;$5*$1$!%$91$12@$3";
    modifyDollarNumber(str);
    std::cout &lt;&lt; "Result : " &lt;&lt; str &lt;&lt; '\n';
}


And I can get the result I want which is

Result : !$@#$35$2%^&amp;$6*$2$!%$92$13@$4
Program ended with exit code: 0


But I want to improve my code so it can be as fast as possible.

How can I simplify modifyDollarNumber() function?
Few observations.

I. You don't need to scan the whole string, character-by-character. str.find('$') will do it for you (and remember to start the second search, and all subsequent ones, from the last reference detected.)

II. Rather than taking substrings, parsing them, erasing and inserting—why not increment in-place? You know exactly your number span (from the one past '$' to the one past the last digit.) If this string only consists of '9's, insert a single '1' right after '$' and change all nines into zeroes. If there are digits less than nine, increment the rightmost non-nine, and change all the subsequent nines into zeroes, if any, no insertion/erasure required. Proceed with the next search.

III. As @AJNeufeld mentioned, string reconstruction can be done in a separate buffer, though vast testing is needed to decide if this is a faster option.