I'm looking for a simple way to tokenize string input without using non default libraries such as Boost, etc.
For example, if the user enters forty_five, I would like to seperate forty and five using the _ as the delimiter.
The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.
String tokenization is a process where a string is broken into several parts. Each part is called a token. For example, if “I am going” is a string, the discrete parts—such as “I”, “am”, and “going”—are the tokens. Java provides ready classes and methods to implement the tokenization process.
The first time the strtok() function is called, it returns a pointer to the first token in string1. In later calls with the same token string, the strtok() function returns a pointer to the next token in the string. A NULL pointer is returned when there are no more tokens. All tokens are null-ended.
strtok() returns a NULL pointer. The token ends with the first character contained in the string pointed to by string2. If such a character is not found, the token ends at the terminating NULL character. Subsequent calls to strtok() will return the NULL pointer.
To convert a string to a vector of tokens (thread safe):
std::vector<std::string> inline StringSplit(const std::string &source, const char *delimiter = " ", bool keepEmpty = false)
{
std::vector<std::string> results;
size_t prev = 0;
size_t next = 0;
while ((next = source.find_first_of(delimiter, prev)) != std::string::npos)
{
if (keepEmpty || (next - prev != 0))
{
results.push_back(source.substr(prev, next - prev));
}
prev = next + 1;
}
if (prev < source.size())
{
results.push_back(source.substr(prev));
}
return results;
}
You can use the strtok_r function, but read the man pages carefully so you understand how it maintains state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With