OneBite.Dev - Coding blog in a bite size

Split A String In C++

Code snippet for how to Split A String In C++ with sample and detail explanation

Splitting a string is a basic programming task that you will frequently be dealing with in C++. C++ offers several ways to perform this operation and in this article, we will discuss and explain one of these methods.

Code snippet for String Split Function in C++

A simple and commonly used function for splitting a string in C++ is demonstrated below:

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

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

std::vector<std::string> split(const std::string &s, char delimiter) {
    std::vector<std::string> elements;
    split(s, delimiter, std::back_inserter(elements));
    return elements;
}

Code Explanation for String Split Function in C++

This code snippet defines two functions, both named ‘split’, to break a given string into words or smaller parts, based on a specified delimiter character.

  1. The first ‘split’ function is a template function. It accepts three parameters - a string that needs to be split, a delimiter character that is used to split the string, and an Output Iterator where the split words from the string will be stored.

  2. The function creates a ‘stringstream’ from the input string. It then uses a while loop to call ‘std::getline’ on the stringstream, which reads characters from the stringstream until the delimiter is encountered.

  3. Inside the loop, for each word obtained from getline(), the word is assigned to the result output iterator. This process is repeated until all words - separated by the delimiter - are stored in the destination represented by the output iterator.

  4. The second ‘split’ function is used to make the split operation easier by providing the destination container implicitly. It uses a ‘vector’ of strings (‘elements’) and merely calls the first ‘split’ function with ‘std::back_inserter(elements)’, which is an insert iterator that allows new elements to be inserted at the end of the vector.

  5. The function then returns the vector that contains the split words from the input string.

These two functions provide a reusable and flexible way to split a string into smaller parts using any specified delimiter in C++.

c-plus-plus