Explode and implode vectors and strings

maddog39 0 Tallied Votes 606 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();
}

Dani AI

Generated

Good starter from — the Boost approach works, but a few practical tweaks make the API safer and faster and avoid common pitfalls (trailing separators, unnecessary copies, and surprising empty tokens).

Use const-correct signatures, avoid trailing separator when joining, and choose whether to keep empty tokens explicitly. A compact, standard-C++ split for a single-character delimiter (no Boost required):

std::vector<std::string> split(const std::string& s, char delim, bool keep_empty = false)
{
    std::vector<std::string> out;
    size_t start = 0;
    for (size_t i = 0; i < s.size(); ++i) {
        if (s[i] == delim) {
            if (keep_empty || i > start)
                out.emplace_back(s.substr(start, i - start));
            start = i + 1;
        }
    }
    if (keep_empty || start < s.size())
        out.emplace_back(s.substr(start));
    return out;
}

A join that avoids a trailing separator and minimizes allocations by reserving space:

std::string join(const std::vector<std::string>& parts, const std::string& sep)
{
    if (parts.empty()) return {};
    size_t total = 0;
    for (const auto& p : parts) total += p.size();
    total += sep.size() * (parts.size() - 1);
    std::string out;
    out.reserve(total);
    for (size_t i = 0; i < parts.size(); ++i) {
        if (i) out += sep;
        out += parts[i];
    }
    return out;
}

Extra tips: reserve the split result with 1 + std::count(s.begin(), s.end(), delim) if performance matters. Use std::string_view (C++17) to avoid allocations when the source string outlives tokens, but note the lifetime caveat. For multi-character separators or regex-like splitting, search with find/substr or a regex engine. Finally, trim tokens or filter empty strings after splitting if you need uniform results across different input edge cases.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.