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

I think I need a reverse strtok version, for example:

char* p = rstrtok(str, delimeters); 

For example, enter the position '-' , '_' and '+' in the line "hello + stack_over-flow" using the set of divisors "+ _-"

I only care about the metrics and their position (and not about the content between them), so I think boost::split_iterator is not suitable here.

Is there any existing utility function that I can use? or any solution to solve this situation?
Also, since I am doing C ++, is there a convenient approach to avoid this old C way?

(I searched for “reverse strtok”, but just “stream down” to “flow through the stack”) ...

+6
source share
3 answers

You can 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 */ } 
+3
source

You can use your own strrchr .

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

+8
source

strtok is quite simple in the most basic versions - just a few hundred lines. If you google "strtok filetype: c", you can see how it is implemented in different libraries.

A very naive solution would be to change the line first and then make strtok (). However, this is bad for long lines, but if you need performance, go to your own strtok ().

Something like that:

 void reverse(char* dest, const char* src) { int len = strlen(src); int i; for(i = 0; i < len; ++i) dest[len-i-1] = src[i]; } 

EDIT:

By the way, I have this Dr Dobbs page open on a tab from a Google search yesterday: http://www.drdobbs.com/conversations-al-go-rithms/184403801

0
source

Source: https://habr.com/ru/post/918325/


All Articles