patterncppMinor
Simple string tokenizer wrapper
Viewed 0 times
wrappersimplestringtokenizer
Problem
Is this orthogonal?
#ifndef TOKENIZER_H
#define TOKENIZER_H
#include
#include
#include
#include
class StringTokenizer
{
private:
std::vector tokens;
unsigned int index;
public:
StringTokenizer(std::string const & str, const char delim)
{
index = 0;
// Populate the token vector...
std::istringstream stream(str);
std::string token;
while (std::getline(stream, token, delim))
{
tokens.push_back(token);
}
}
~StringTokenizer(void) { };
bool HasMoreTokens() { return index < tokens.size(); };
std::string NextToken() { return TokenAtIndex(index++); };
std::string PreviousToken() { return TokenAtIndex(index--); };
std::string TokenAtIndex(int x)
{
std::string token = "";
try
{
token = tokens.at(x);
}
catch (const std::out_of_range& range_error)
{
std::cerr << "[!!] Out of Range: " << range_error.what() << std::endl;
}
return token;
}
void Clear() { index = 0; };
};
#endifSolution
Your constructor is nigh-identical to this up-voted answer for splitting a string.
The rest of the class doesn't add much value: IMO the vector provides the same API as your class and more besides; so a user might prefer to have the vector than to have your StringTokenizer instance which wraps/encapsulates/hides the vector.
The rest of the class doesn't add much value: IMO the vector provides the same API as your class and more besides; so a user might prefer to have the vector than to have your StringTokenizer instance which wraps/encapsulates/hides the vector.
vector.at returns a const reference, instead of returning by value: perhaps your methods should too.Context
StackExchange Code Review Q#43561, answer score: 4
Revisions (0)
No revisions yet.