C language: How to get the remaining string after using strtok() once

27,721

Solution 1

You can vary the set of delimiters, so simply pass an empty string:

char a[] = "A,B,C,D,E";
char * separator = ",";
char * b = strtok(a, separator);
printf("b: %s\n", b);
char * c = strtok(NULL, "");
printf("c: %s\n", c);

Solution 2

Don't use strtok() for this, since that's not what it's for.

Use strchr() to find the first separator, and go from there:

char a[] = "A,B,C,D,E";
const char separator = ',';
char * const sep_at = strchr(a, separator);
if(sep_at != NULL)
{
  *sep_at = '\0'; /* overwrite first separator, creating two strings. */
  printf("first part: '%s'\nsecond part: '%s'\n", a, sep_at + 1);
}

Solution 3

Try this:

char a[] = "A,B,C,D,E";
char * end_of_a = a + strlen(a); /* Memorise the end of s. */
char * separator = ",";
char * b = strtok(a, separator);
printf("a: %s\n", a);
printf("b: %s\n", b);

/* There might be some more tokenising here, assigning its result to b. */

if (NULL != b)
{
  b = strtok(NULL, separator);
}

if (NULL != b)
{ /* Get reference to and print remainder: */
  char * end_of_b = b + strlen(b);

  if (end_of_b != end_of_a) /* Test whether there really needs to be something, 
                        will say tokenising did not already reached the end of a, 
                        which however is not the case for this example.  */
  {
    char * remainder = end_of_b + 1;
    printf("remainder: `%s`\n", remainder);
  }   
}

Solution 4

strtok remembers the last string it worked with and where it ended. To get the next string, call it again with NULL as first argument.

char a[] = "A,B,C,D,E";
const char *separator = ",";
char *b = strtok(a, separator);
while (b) {
    printf("element: %s\n", b);
    b = strtok(NULL, separator);
}

Note: This is not thread safe.

Share:
27,721
Eric Tseng
Author by

Eric Tseng

Updated on March 10, 2021

Comments

  • Eric Tseng
    Eric Tseng over 3 years

    My string is "A,B,C,D,E"
    And the separator is ","
    How can I get the remaining string after doing strtok() once, that is "B,C,D,E"

    char a[] = "A,B,C,D,E";
    char * separator = ",";
    char * b = strtok(a,separator);
    printf("a: %s\n", a);
    printf("b: %s\n", b);
    

    The output is:
    a: A
    b: A

    But how to get the result
    a: B,C,D,E
    b: A

    Thanks.