Tuom L.
Tuom L.

Reputation: 182

C++ helper function

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);

Upvotes: 1

Views: 2782

Answers (2)

Xymostech
Xymostech

Reputation: 9850

I just want to point out that your macro would have worked, you just used it incorrectly. However, this is not the right way to solve this problem, just wanted to point it out. Here's the correct usage:

#define REPLACE .replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = myString1 REPLACE;

Or maybe better (if using macros can ever be better):

#define REPLACE(str) str.replace("a", "b").replace("c", "d").replace("e", "f")
otherString1 = REPLACE(myString1);

Remember, don't do this, but this is how macros could be used.

Upvotes: 1

NPE
NPE

Reputation: 500167

IMO, you are overthinking it. Just create a function that takes a string (by const reference) and returns the modified string. Declare it in a header and define in the corresponding .cpp file.

Job done.

[helper.hpp]
std::string myReplace(const std::string& s);

[helper.cpp]
std::string myReplace(const std::string& s) {
   ...
}

[somefile.cpp]
#include "helper.hpp"
otherString3 = myReplace(myString3);

Upvotes: 5

Related Questions