I have lots of code like this:
otherString1 = myString1.replace("a", "b").replace("c", "d").replace("e", "f");
otherString2 = myString2.replace("a", "b").replace("c", "d").replace("e", "f");
otherString3 = myString3.replace("a", "b").replace("c", "d").replace("e", "f");
I would like to not repeat those replace
methods again and again. What is the right approach to re-factoring of such code? I'm new to C++...
I thought I could do:
#define REPLACE .replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = myString1#REPLACE;
but this does not work.
I obviously cannot monkey-patch the string class to add myReplace()
...
What to do? And should I put the replacement code into header or the sourse file? What about those static
, inline
, const
things? Should I create a whole helper class and a helper method or should I create just a function somewhere? What about something like:
[helper.hpp]
static inline const myReplace(const StringClass s);
[helper.cpp]
static inline const myReplace(const StringClass s) {
return s.replace("a", "b").replace("c", "d").replace("e", "f");
}
[somefile.cpp]
include "helper.hpp"
otherString3 = myReplace(myString3);