4

what I want to do is given an input string, which I will not know it's size or the number of tokens, be able to print it's last token.

e.x.:

char* s = "some/very/big/string";
char* token;

const char delimiter[2] = "/";

token = strtok(s, delimiter);

while (token != NULL) {
    printf("%s\n", token);
    token = strtok(NULL, delimiter);
}

return token;

and i want my return to be

string

but I what I get is (null). Any workarounds? I've searched the web and can't seem to find an answer to this. At least for C programming language.

Jack
  • 722
  • 3
  • 8
  • 24

2 Answers2

22

If you tokenize on a specific character, i.e. '/' in your example, you do not need to tokenize the string at all: call strrchr to find the position of the last '/', and add 1 to the resultant pointer to skip the delimiter, like this:

char *s = "some/very/big/string";
char *last = strrchr(s, '/');
if (last != NULL) {
    printf("Last token: '%s'\n", last+1);
}

Demo.

AntonioCS
  • 8,335
  • 18
  • 63
  • 92
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

Just use another variable to store last token before it gets null

char s[] = "some/very/big/string";
char * token, * last;
last = token = strtok(s, "/");
for (;(token = strtok(NULL, "/")) != NULL; last = token);
printf("%s\n", last);
hlscalon
  • 7,304
  • 4
  • 33
  • 40
  • 1
    @bisuke It's a simplification. You could rewrite it to something like: `while(token != NULL) { last = token; token = strtok(NULL, "/"); } ` – hlscalon Jun 06 '16 at 14:27