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

后端 未结 6 1793
名媛妹妹
名媛妹妹 2021-02-13 16:42

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,         


        
相关标签:
6条回答
  • 2021-02-13 17:04

    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);
    
    0 讨论(0)
  • 2021-02-13 17:15

    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.

    0 讨论(0)
  • 2021-02-13 17:21

    printf("a: %s\n", a+1+strlen(b));

    Try this

    0 讨论(0)
  • 2021-02-13 17:23

    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);
      }   
    }
    
    0 讨论(0)
  • 2021-02-13 17:30

    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);
    }
    
    0 讨论(0)
  • 2021-02-13 17:31

    If using strtok is not a requirement, you can use strchr instead since the separator is a single character:

    char a[] = "A,B,C,D,E";
    char *sep = strchr(a, ',');
    *sep = '\0';
    puts(a);
    puts(sep + 1);
    
    0 讨论(0)
提交回复
热议问题