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 <iostream>
#include <string>
void modifyDollarNumber(std::string &str)
{
for (size_t i = str.length(); i --> 0 ;)
{
if (str[i] == '$')
{
size_t j = i + 1;
while (j < str.length() && 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%^&$5*$1$!%$91$12@$3";
modifyDollarNumber(str);
std::cout << "Result : " << str << '\n';
}
And I can get the result I want which is
Result : !$@#$35$2%^&$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?