Monday, December 8, 2014

Tokenize a C++ std::string

There are a lot of ways to tokenize a string, and this isn't necessarily the best but it works easily for what it does.

std::list Split(std::string Value, std::string Delimiter)
{
    std::list result;
    std::vector buffer(Value.c_str(), Value.c_str() + Value.size() + 1);
    char *p = strtok(&buffer[0], Delimiter.data());
    
    while (p != NULL)
    {
        std::string token = p;
        result.push_back(token);
        p = strtok(NULL, Delimiter.data());
    }
    
    return result;
}

Call this like this:


    std::list items = Split("foo/goo/boo/foo", "/");

    for (std::list::const_iterator iterator = items.begin();
         iterator != items.end();
         iterator++)
    {
        std::string line = *iterator;
        printf("%s\n", line.c_str());
    }

And it will print out this:

foo
goo
boo
moo


Note: Yes, I do like to mix C and C++ :)

No comments:

Post a Comment