bli00
bli00

Reputation: 2787

How to use strtok() tokens

As per this description, strtok() delimitate a string into tokens by the delimiter given, returns a pointer to the first token found in the string. All subsequent tokens need to be traversed via a loop, like the example code given in the link.

Does each token auto terminate with NULL? i.e. can I simply assign each token to a variable and use it or does it need strncpy() to be copied to an allocated space?

For example, would this be valid?

   char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";
   char *token;

   char *test[4];
   int test_count = 0;
   memset(test, 0x00, 4);

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) {
      test[test_count] = token;
      test_count++;
      token = strtok(NULL, s);
   }

Upvotes: 2

Views: 988

Answers (1)

user2371524
user2371524

Reputation:

strtok() works on your original input string, by replacing the first occurence of a character in the list of delimeters with a '\0'. So yes, this is the intended usage as you describe it.

Side notes:

  • don't write things like

    const char s[2] = "-";
    

    just using

    const char s[] = "-";
    

    lets the compiler determine the correct size automatically

  • in this special case, just passing "-" to strtok() (or a #define to "-") would do fine, a decent compiler recognizes identical string literals and creates only one instance of them.

  • just in case it's helpful to see some code, here's a simple strtok implementation I did myself a while back.

Upvotes: 2

Related Questions