Hi and this function I wrote as part of a larger project and acts exactly like the php explode function. Although there a few slight differences between this function and the php explode function it can easily be tweaked to act identical. Also with this function it does not use vectors. Instead it uses an array as the result and in the result array, the combination being split will not appear in any of the strings just like the php function does.

In case your wondering how to use this function simply place in the string to split (param1) and where to split it (param2) then it will return an string array with the results. Hope you enjoy this function and that this page is a good reference...

Comments
Nice :)
#include <string>
std::string *explode (std::string original, std::string exploder=".") {
	std::string tmp;
	tmp=original;
	int num, loc;
	num=1;
	while (tmp.find(exploder)!=std::string::npos) {
		loc=tmp.find(exploder);
		tmp=tmp.substr(loc+exploder.length());
		num++;
		}
	std::string *result;
	result = new std::string[num];
	num=0;
	tmp=original;
	while (tmp.find(exploder)!=std::string::npos) {
		loc=tmp.find(exploder);
		result[num]=tmp.substr(0,loc);
		tmp=tmp.substr(loc+exploder.length());
		num++;
		}
	result[num]=tmp;
	return result;
}

Really nice, thank you! I'm programming a simple server for a game of mine and I use it to get arguments from headers :3.

Why didn't you use a vector as a return-value? It seems like the logic way to go, since you can easily find out how many strings were found, which is sort of a guessing game now.

Just as a suggestion:

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

std::vector<std::string> explode (std::string original, unsigned char exploder='.') {
    std::stringstream sstr(original);
    std::vector<std::string> ret_val;
    std::string buffer = "";
    while (std::getline(sstr, buffer,exploder)) 
        ret_val.push_back(buffer);
    
    return ret_val;
}

int main() {
    std::string test = "hai.test.test.testing";
    std::vector<std::string> v = explode(test);

    std::cout << "Found " << v.size() << " words: \n";
    for (size_t i = 0; i != v.size(); ++i) 
        std::cout << v.at(i) << '\n';
}

(untested...)

Edited 6 Years Ago by Nick Evan: n/a

Just a minor point:

php explode has a third optional parameter that limits the number of times to split

http://www.tizag.com/phpT/php-string-explode.php
so

std::vector<std::string> php_explode(const std::string &divide,
 const std::string &to_explode, int max_number = -1);

would be closer to the php_function signature but an easy modification to Nick's code

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.