Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reversely strtok a C++ string from tail to head?

Tags:

c++

strtok

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...)

like image 738
Lyn Avatar asked Jun 18 '12 06:06

Lyn


People also ask

How does strtok work in C++?

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.

How to reverse a C-string in Python?

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.

Why does strtok () keep returning non null pointers?

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.

What is the difference between strtok () and *strict Sep ()?

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.


2 Answers

You could roll your own using strrchr.

If you use C++ style std::string you can leverage string::find_last_of.

like image 136
dirkgently Avatar answered Oct 01 '22 03:10

dirkgently


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 */
}
like image 25
Some programmer dude Avatar answered Oct 01 '22 03:10

Some programmer dude