Backtracking in a String with the strtoc_r Function

Hello!

I am using the strtok_r function to grab space-separated tokens from a string. However, I would like to be able to go backwards (to a known point) as well. How can I do this? If i'm able to grab a pointer to the word I'm looking to backtrack to, will that help me?

Sorry, I got the strtok_r function working, but I still don't really understand how it works :confused:

Thanks!

(I'm using strtok_r instead of strtok because it needs to be threadsafe :slight_smile: )

I'm using strtok_r instead of strtok because it needs to be threadsafe

Really? On the Arduino where there is ONLY one thread?

PaulS:
Really? On the Arduino where there is ONLY one thread?

Not a thread, but recursion, which needs threadsafe functions.

strtok saves state, which is why it is not thread safe. Calling it multiple times on the same input makes no sense.

Why not just write your own? It is not that hard.

eta:
Also recursion sucks up stack space, which is in short supply on most AVR's.

Yes. strtok uses a global variable to store its position.
strtok_r, however, does not.
Also, having an answer to the topic question would help me reduce the recursion drastically.

It does not sound to me like you want to "back up" in the string. It sounds to me like you want to start over parsing the string based on what you find later in the string. I don't understand that.

Post an example of what you are trying to parse, and explain why you need to "back up" in the parsing.

It seems silly, and is obvious from the docs (strtok_r() saves no state), that if you just stash the saveptr argument, you can restart the parsing from anywhere you like.

Unless I'm very much mistaken.... all variations of strtok clobber the source string. When they find the specified delimiter, they replace it with a NULL. So, "backtracking" is impossible, as the original string no longer exists after the first call to strtok.

Regards,
Ray L.

RayLivingston:
Unless I'm very much mistaken.... all variations of strtok clobber the source string. When they find the specified delimiter, they replace it with a NULL. So, "backtracking" is impossible, as the original string no longer exists after the first call to strtok.

Regards,
Ray L.

Oops, you are right, you would need to store the string and the next pointer to start a rescan.