0

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

1

2 Answers 2

3

Working example with regexes, compile with g++ -std=c++11 test.cpp:

#include <iostream> #include <string> #include <regex> std::string replaceDollarNumber(std::string str, std::string replace) { std::regex long_word_regex("(\\$[0-9]+)"); std::string new_s = std::regex_replace(str, long_word_regex, replace); return new_s; } int main() { std::string str = "!$@#$34$1%^&$5*$1$!%$91$12@$3"; auto new_s = replaceDollarNumber(str, "<>"); std::cout << "Result : " << new_s << '\n'; } 
Sign up to request clarification or add additional context in comments.

Comments

0

The code has two problems. First, the second argument to basic_string::erase should be the length of the text to be erased; this function calls it with the index of the last character to be erased. Second, the code inserts the replacement text even if there were no digits found.

Fixing those two problems gives this:

void replaceDollarNumber(std::string &str, std::string replace) { size_t pos; while ((pos = str.find('$')) != std::string::npos) { size_t end = pos + 1; while (end < str.length() && isdigit(str[end])) { end++; } if (end != pos + 1) { str.erase(pos, end - pos); str.insert(end, replace); } } } 

I've renamed len to end to better reflect its actual meaning.

I haven't tested the code; I think end - pos is correct, but it could be off by one.

Finally, I'd use basic_string::replace instead of erase and insert.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.