3

I have a std::string A I need to find in it string B with content like bla-bla-bla and replace it with other string C like abcdefg and if B was not found just put C at the beginning of A.

How to do such thing?

2
  • it is use full when you have some ones url and you want to make it use something like 'rtmp://' instead of 'http://' and ofcourse you newer know if 'http://'.) Commented Nov 17, 2010 at 22:16
  • 3
    Have you looked at string::replace and string::find? Commented Nov 17, 2010 at 22:16

2 Answers 2

4
void replace_or_merge(std::string &a, const std::string &b, const std::string &c) { const std::string::size_type pos_b_in_a = a.find(b); if(pos_b_in_a == std::string::npos) { a.insert(0, c); } else { a.replace(pos_b_in_a, b.length(), c); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 / sounds logic, but better to pass b and c as const std::string&
2
A.replace(str.find(B), B.length(), C); 

You might want to add error checking ;-)

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.