Archived

This topic is now archived and is closed to further replies.

FireSlash

Explode() for C++? (aka split())

Recommended Posts

Sneftel    1788
Well, not that hard; you can just search through for the character you want. But if you don''t wanna do that yourself, check out the C function strtok() and the Boost::Tokenizer library.


Don''t listen to me. I''ve had too much coffee.

Share this post


Link to post
Share on other sites
Null and Void    1088
I got bored :

  
#include <algorithm>


template <typename ContType, typename CharType>
void explode(ContType &Output, const CharType *Begin, const CharType *End, const CharType *SBegin, const CharType *SEnd) {
while(Begin < End) {
const CharType *Next = std::search(Begin,End,SBegin,SEnd);

Output.push_back(std::string(Begin,(Next-Begin)));

Begin = Next+1;
}
}

template <typename ContType, typename CharType>
inline void explode(ContType &Output, const CharType *Begin, const CharType *End, CharType Symbol) {
explode(Output,Begin,End,&Symbol,&Symbol + 1);
}

// DEMO:

#include <iostream>

#include <iterator>

#include <algorithm>

#include <list>

#include <string>


int main(void) {
const char Data[] = "Value|Morestuff|WEEE!|OMGoO|Result";
std::list <std::string> Exploded;

explode(Exploded, &Data[0], &Data[sizeof(Data)], ''|'');

std::copy(Exploded.begin(), Exploded.end(), std::ostream_iterator<std::string>(std::cout,"\n"));

return 0;
}


Hopefully that gets through the mangling okay...

Share this post


Link to post
Share on other sites