C - Determining which delimiter used - strtok()

前端 未结 3 1575
攒了一身酷
攒了一身酷 2021-02-14 08:05

Let\'s say I\'m using strtok() like this..

char *token = strtok(input, \";-/\");

Is there a way to figure out which token actually

3条回答
  •  面向向阳花
    2021-02-14 08:42

    You can't. strtok overwrites the next separator character with a nul character (in order to terminate the token that it's returning this time), and it doesn't store the previous value that it overwrites. The first time you call strtok on your example string, the ; is gone forever.

    You could do something if you keep an unmodified copy of the string you're modifying with strtok - given the index of the nul terminator for your current token (relative to the start of the string), you can look at the same index in the copy and see what was there.

    That might be worse than just writing your own code to separate the string, of course. You can use strpbrk or strcspn, if you can live with the resulting token not being nul-terminated for you.

提交回复
热议问题