Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to split a sequence of null-separated strings in C++

Tags:

c++

std

stl

I have a series of strings stored in a single array, separated by nulls (for example ['f', 'o', 'o', '\0', 'b', 'a', 'r', '\0'...]), and I need to split this into a std::vector<std::string> or similar.

I could just write a 10-line loop to do this using std::find or strlen (in fact I just did), but I'm wondering if there is a simpler/more elegant way to do it, for example some STL algorithm I've overlooked, which can be coaxed into doing this.

It is a fairly simple task, and it wouldn't surprise me if there's some clever STL trickery that can be applied to make it even simpler.

Any takers?

like image 937
jalf Avatar asked Aug 30 '11 13:08

jalf


2 Answers

My two cents :

const char* p = str;
std::vector<std::string> vector;

do {
  vector.push_back(std::string(p));
  p += vector.back().size() + 1;
} while ( // whatever condition applies );
like image 69
slaphappy Avatar answered Nov 10 '22 04:11

slaphappy


Boost solution:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
//input_array must be a Range containing the input.
boost::split(
    strs,
    input_array,
    boost::is_any_of(boost::as_array("\0")));
like image 21
Mankarse Avatar answered Nov 10 '22 05:11

Mankarse