I want to replace all occurrences of '$' with "$$". Currently I am using string::find to check if '$' is present in string or not. then I am using for loop and checking every character if it matches with '$'. If a character matches with $ then I am using string::replace to replace it. Is there any other effective method to do this in c++? without traversing entire string with less complexity?
1 Answer
I don't know a standard function which replaces ALL occurrences of a certain string with another string. The replace-functions either replace all occurrences of a specific character by another character, or replace a single range of characters with another range.
So I think you cannot avoid iterating through the string on your own. In your specific case, it might be easier, as you just have to insert an additional $ for every $-character you find. Note the special measure avoiding an endless loop, which would happen if one doubled also the $-value just inserted again and again:
int main() { string s = "this $ should be doubled (i.e. $), then. But $$ has been doubled, too."; auto it = s.begin(); while (it != s.end()) { if (*it == '$') { it = s.insert(it, '$'); it += 2; } else { it++; } } cout << s; } 2 Comments
std::find, of course, which gives you the next occurrence of a character. But anyway, even std::find will traverse the string and check each character. I'm quite sure that this doesn't make things clearer or in another way better...
std::replaceto achieve what you want to.std::replacefor replacing one character with another one, but not for replacing a single character with a string like"$$"?