Explode and implode vectors and strings

maddog39 0 Tallied Votes 524 Views Share

This snippet will allow you to separate or "explode" strings into vectors via a character separator or the visa versa. In which case you would take a vector and "implode" it into a string separated by a character. Also keep in mind that this requires the libboost libraries. This was tested on Linux using the GNU C++ compiler. Below is an example of its usage:

#include <iostream>
#include "implode_explode.h"

int main(int argc, char *argv[])
{
	std::string mystring = "this-is-a-test-string";
	std::vector<std::string> myvector = explode("-", mystring);
	std::vector<std::string>::iterator myvector_iter;
	std::string mynewstring = implode(" ", myvector);
	
	std::cout << "Original String: " << mystring << std::endl;
	
	for (myvector_iter = myvector.begin(); myvector_iter != myvector.end(); myvector_iter++)
		std::cout << "Exploded String: " << *myvector_iter << std::endl;
	
	std::cout << "Imploded Vector: " << mynewstring << std::endl;
	
	return 0;
}

Output of the program is:

Original String: this-is-a-test-string
Exploded String: this
Exploded String: is
Exploded String: a
Exploded String: test
Exploded String: string
Imploded Vector: this is a test string
#include <string>
#include <vector>
#include <sstream>
#include <boost/tokenizer.hpp>

static std::vector<std::string> explode(char *sep, std::string src)
{
	std::vector<std::string> output;
	boost::char_separator<char> separator(sep);
	boost::tokenizer<boost::char_separator<char> > tokens(src, separator);
	boost::tokenizer<boost::char_separator<char> >::iterator token_iter;
	
	for (token_iter = tokens.begin(); token_iter != tokens.end(); token_iter++)
		output.push_back(*token_iter);
	
	return output;
}
	
static std::string implode(char *sep, std::vector<std::string> src)
{
	std::ostringstream output;
	std::vector<std::string>::iterator src_iter;
	
	for (src_iter = src.begin(); src_iter != src.end(); src_iter++)
		output << *src_iter << sep;
	
	return output.str();
}