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,
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);
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.
printf("a: %s\n", a+1+strlen(b));
Try this
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);
}
}
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);
}
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);