0

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?

9
  • 1
    @George exactly! here, there is no need to find the occurrences and then replace them. You could rather just use std::replace to achieve what you want to. Commented Nov 8, 2017 at 7:44
  • 3
    I doubt that it's possible to do this without traversing the entire string. How are you going to check every character otherwise? If you call some function to do it, that function will effectively do the traversal for you. Commented Nov 8, 2017 at 7:48
  • Neha: could you edit your question to explain why it is not a duplicate of linked thread? Commented Nov 8, 2017 at 7:50
  • 1
    @Robin: Isn't std::replace for replacing one character with another one, but not for replacing a single character with a string like "$$"? Commented Nov 8, 2017 at 8:03
  • 3
    dup stackoverflow.com/questions/3418231/… Commented Nov 8, 2017 at 8:10

1 Answer 1

0

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; } 
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, I did exactly same. But here we are checking all characters, right? I am asking that instead of traversing entire string , is it possible to do this?
you could use 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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.