I'm trying to find substrings in a string and then replace them with other string.
The substring I'm looking for has $ + number format.
For example, $1250, $512, $0, etc..
I would like to detect these substrings from string and then replace them with other string.
My Code :
#include <iostream> void replaceDollarNumber(std::string &str, std::string replace) { size_t pos; while ((pos = str.find('$')) != std::string::npos) { size_t len = pos + 1; while (len < str.length() && isdigit(str[len])) { len++; } str.erase(pos, --len); str.insert(pos, replace); } } int main() { std::string str = "!$@#$34$1%^&$5*$1$!%$91$12@$3"; replaceDollarNumber(str, "<>"); std::cout << "Result : " << str << '\n'; } Result I expect :
Result : !$@#<><>%^&<>*<>$!%<><>@<> Result I get :
Result : !<>@#<>&<>91<> How can I correct the replaceDollarNumber function so I can get the result I want?
Also, I would like to know if there's more performant solution.
EDITED: I would also like to know how to do this without using regex