Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

strtok

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.

like image 580
Eric Tseng Avatar asked Nov 01 '13 09:11

Eric Tseng


People also ask

How do you get next token in strtok?

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.

Does strtok return a string?

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.

What does strtok () do in C?

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.

Does strtok destroy the string?

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.


2 Answers

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);
like image 172
Neil Avatar answered Sep 20 '22 23:09

Neil


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);
}
like image 25
unwind Avatar answered Sep 16 '22 23:09

unwind