0 Replies - 1985 Views - Last Post: 02 March 2012 - 03:38 PM

#1 anonymouscodder  Icon User is offline

  • member icon

Reputation: 126
  • View blog
  • Posts: 710
  • Joined: 01-January 10

C++ string tokenizer

Posted 02 March 2012 - 03:38 PM

Description: A C++ string tokenizer
#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> tokenize(const char* str, char delimiter) {
    std::vector<std::string> tokens;
    do {
        const char* c = str;
        while(*str && *str != delimiter)
            ++str;
        std::string token(c, str);
        if(token.size())
            tokens.push_back(token);
    } while(*str++);
    return tokens;
}

/*
Output:
asterisk
separated
string
as
example

*/
int main() {
    std::vector<std::string> tokens = tokenize("***asterisk**separated*string*as**example***", '*');
    for(std::vector<std::string>::iterator i = tokens.begin(); i < tokens.end(); ++i)
        std::cout << *i << std::endl;
    return 0;
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1