Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a string in string and replace it?

Tags:

c++

string

boost

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?

like image 982
Rella Avatar asked Jun 03 '26 20:06

Rella


2 Answers

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);
  }
}
like image 193
J. Calleja Avatar answered Jun 06 '26 09:06

J. Calleja


A.replace(str.find(B), B.length(), C);

You might want to add error checking ;-)

like image 45
fredoverflow Avatar answered Jun 06 '26 10:06

fredoverflow