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.
The strtok() function gets the next token from string s1, where tokens are strings separated by characters from s2. To get the first token from s1, strtok() is called with s1 as its first parameter. Remaining tokens from s1 are obtained by calling strtok() with a null pointer for the first parameter.
Returned valueThe first time strtok() is called, it returns a pointer to the first token in string1. In later calls with the same token string, strtok() returns a pointer to the next token in the string. A NULL pointer is returned when there are no more tokens. All tokens are NULL-terminated.
The strtok() function parses the string up to the first instance of the delimiter character, replaces the character in place with a null byte ( '\0' ), and returns the address of the first character in the token. Subsequent calls to strtok() begin parsing immediately after the most recently placed null character.
Yes, strtok destroys the string it is working on. If you want to have the original untouched, then make a copy and use strtok on the copy.
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);
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With