IAA_ IAA_ - 20 days ago 6
C++ Question

How to remove a substring from a string using a template function?

I am able to do this:

template <typename T>

T add (T x, T y) {
T z = x + y;
return z;
}

int main() {
string string1 = "stack";
string string2 = "overflow";
cout << add<string> (string1, string2);
}


I get "stackoverflow".

How do I similarly use a template function for removing a substring from a string (that can also be used with integers, floats etc.) ? For example, remove "overflow" from "stackoverflow".

Answer

How do I similarly use a template function for removing a substring from a string (that can also be used with integers, floats etc.) ? For example, remove "overflow" from "stackoverflow".

You can do that using a simple function like:

std::string remove(const std::string& toRemove, const std::string& original) {
    std::string result(original);
    size_type pos = original.find(toRemove);
    if(pos != std::string::npos) {
         result = original.substr(0,pos);
    }
    return result;
}

that overloads a templated version, which will apply for float, int, etc.:

template<typename T> T remove(const T& toRemove, const T& original) {
    return original - toRemove;
}

See a Live Demo.

Comments