I think I need a reverse version of strtok, like:
char* p = rstrtok(str, delimeters);
For example, sequentially get the position of '-', '_' and '+' in the string "hello+stack_over-flow" using a delimeter set of "+_-"
I only care about the delimeters, and their position, (not the content between), so I guess the boost::split_iterator is not appropriate here.
Is there any existing utility function I can leverage? or any solution to deal with this kind of situation?
Furthermore, since I am doing C++, is there any convenient approach to avoid this old fashion C?
(I searched "reverse strtok" but merely get "stack over flow" to "flow over stack" stuff...)
When a chunk of the string is found (or separated), strtok () returns a pointer. The pointer references only a specific chunk of text, not the rest of the string. The strtok () function at Line 11 scans the text in variable string. It’s looking for the space character as a separator.
In this quick article, we’ll explore how to reverse a C-String, which is a null-terminated ('\0') block of a contiguous sequence of characters. The standard solution is to loop through the first half of the given C-string using a loop and swap the current character with the corresponding character on the other half of the C-string.
As long as strtok () keeps returning non-NULL char pointers, you continue to call the function to search for more text. When a chunk of the string is found (or separated), strtok () returns a pointer. The pointer references only a specific chunk of text, not the rest of the string.
The *restrict str is the string to search. The *strict sep is a string consisting of one or more separator characters. The function returns a char pointer to the first character in the string that’s not a separator character. And like most parsing functions I’ve seen, strtok () is called multiple times until the entire string is parsed.
You could roll your own using strrchr.
If you use C++ style std::string you can leverage string::find_last_of.
You could do this with strpbrk:
char string[] = "hello+stack_over-flow";
char *pos = string;
while (*pos != '\0' && (pos = strpbrk(pos, "+-_")) != NULL)
{
/* Do something with `pos` */
pos++; /* To skip over the found character */
}
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