How to Split a string in C++?

Created:

Introduction

In this tutorial we are going to show how to split a string separated by spaces. We will focus on an elegant solution for this problem and we will not any C function.

For the solution we will use standard library.

Our last example accept any char as delimiter.

Split string using std

In the next example we use istream_iterato, which is a single-pass input iterator that reads successive objects by calling the appropriate operator>>. The istringstream will create a stream from the string and uses white space to separete elements or tokens from the strings. We will store the result in a vector clled tokens. The copy function will stop when the end-of-string was found while doing the iteration, that's why the second argument is istream_iterator(). Remember that the default constructor of the istream creates the end-of-steam iterator. This solution only accepts white space as delimiter.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "Tutorials technology learn with example";
    istringstream iss(sentence); // we create the iterator
    vector<string> tokens; // we will save the results
    copy(istream_iterator<string>(iss),
         istream_iterator<string>(), //end-of-stream
         back_inserter(tokens)); // we use back_inserter to preserve the original order.

    return 0;
}

Alternative without sing istream_iterator

As you can see in this alternative we use operator>> instead the istream_iterator. The next code is very similar to the previous one, it only accepts white space as delimiter:

#include <vector>
#include <string>
#include <sstream>

int main()
{
    std::string original_text("Tutorials technology learn with example");
    std::string buf; // we need a temp buffer for the iteration on the while    
    std::stringstream original_text(str); // we create a stringstream of the string

    std::vector<std::string> tokens; 

    // instead of using copy we iterate the string using the operator>>
    while (ss >> buf)
        tokens.push_back(buf);

    return 0;
}

Generic solution that accepts any delimiter char

In the next code we can use any delimiter char:

#include <string>
#include <sstream>
#include <vector>
#include <iterator>

template<typename Out>
void split(const std::string &s, char delim, Out result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        *(result++) = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> tokens;
    split(s, delim, std::back_inserter(elems));
    return tokens;
}