In this article we will see 2 techniques to split a std::string in C++ and return the result in std::vector<std::string> i.e.

  • Splitting a std::string using a char as delimiter.
  • Splitting a std::string using an another std::string as delimiter.

How to Split a std::string using a char as delimiter:

In this we will convert the passed string into a stringstream and from that string stream we will fetch each word using getline method,

But wait a minute, above function splits a string by a character delimiter but what if I want to split it based on another string,

like if first string is “Lets split this line using split functions” then on splitting it with “split” delimiter the result should be,

“Lets”

“this line using”

“functions”

To achieve this we have to write an another split function with std::string as delimiter i.e.

How to split a string by another string as delimiter:

In the above code we will search for the delimiters in the passed string and fetch the sub strings in between them.

Complete executable code is as follows,

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

/*
std::string split implementation by using delimeter as a character.
*/
std::vector<std::string> split(std::string strToSplit, char delimeter)
{
    std::stringstream ss(strToSplit);
    std::string item;
	std::vector<std::string> splittedStrings;
    while (std::getline(ss, item, delimeter))
	{
		splittedStrings.push_back(item);
    }
	return splittedStrings;
}

/*
std::string split implementation by using delimeter as an another string
*/
std::vector<std::string> split(std::string stringToBeSplitted, std::string delimeter)
{
	std::vector<std::string> splittedString;
	int startIndex = 0;
	int  endIndex = 0;
	while( (endIndex = stringToBeSplitted.find(delimeter, startIndex)) < stringToBeSplitted.size() )
	{

		std::string val = stringToBeSplitted.substr(startIndex, endIndex - startIndex);
		splittedString.push_back(val);
		startIndex = endIndex + delimeter.size();

	}
	if(startIndex < stringToBeSplitted.size())
	{
		std::string val = stringToBeSplitted.substr(startIndex);
		splittedString.push_back(val);
	}
	return splittedString;

}

int main()
{
	std::string str = "Lets split this line using split functions";

	// Spliting the string by ''
	std::vector<std::string> splittedStrings = split(str, ' ');
	for(int i = 0; i < splittedStrings.size() ; i++)
		std::cout<<splittedStrings[i]<<std::endl;

	// Spliting the string by an another std::string
	std::vector<std::string> splittedStrings_2 = split(str, "split");
	for(int i = 0; i < splittedStrings_2.size() ; i++)
		std::cout<<splittedStrings_2[i]<<std::endl;	

	return 0;

}