Efficiently splitting a string in C++ I've made a splitString() function which receives a character and a string and returns a vector&lt;string&gt; containing all the string split by a character in the input string:
vector&lt;string&gt; splitString(string input, char separator) {

    size_t pos;
    vector&lt;string&gt; text;

    while (!input.empty()) {

        pos = input.find(separator); //find separator character position

        if (pos == string::npos) {
            text.push_back(input);
            break;
        }
        text.push_back(input.substr(0, pos));

        input = input.substr(pos + 1);
    }
    return text; //returns a vector with all the strings
}

Example Input(.csv):
name;surname;age

Output would be:
vector&lt;string&gt; contains {name, surname, age}

Is there any efficient way of doing this?
As you can see, the ; was deleted separating the strings.
I was wondering if there is any way of adding an option to NOT delete the separator character, including it in the split strings.
What are the expensive operations you do?

Allocating memory for the copy of a std::string passed into splitString().
This can be fixed by accepting a std::string_view instead, or at least a constant reference instead of a copy.
See How exactly is std::string_view faster than const std::string&amp;? and What is string_view? for details.

Allocating memory for the std::strings stored in the result-vector.
Those might be replacable with std::string_view if the argument is changed, but no guarantees. This would be a significant usage change.

Repeatedly shuffling all the rest of the string to the front when removing a match.
Just find the target and copy / reference from there.

Constructing the result-elements in-place using .emplace_back() can also save some effort.


Adding the option to not remove the separator would only really make sense if you allow multiple separators.
Regarding your code, I'm not sure whether you use the dreaded using namespace std;, or the far more benign using std::string; using std::vector;.
If the former, see Why is “using namespace std;” considered bad practice?.
One behavioral point I changed: You ignore the last entry if empty. I decided to preserve it always, thus even an empty string gets at least one result.
auto splitString(std::string_view in, char sep) {
    std::vector&lt;std::string_view&gt; r;
    r.reserve(std::count(in.begin(), in.end(), sep) + 1); // optional
    for (auto p = in.begin();; ++p) {
        auto q = p;
        p = std::find(p, in.end(), sep);
        r.emplace_back(q, p);
        if (p == in.end())
            return r;
    }
}