Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Strtok for tokenizing a Const char*?

Tags:

I have a const char* variable which may have a value like "OpenStack:OpenStack1". I want to tokenize this const char* using strtok where the delimiter(which is of a const char* type) is ":" . But the problem is strtok is of following type: char * strtok ( char * str, const char * delimiters );

Which means I can't use const char* for the first input as it has to be char*. Could you say me how I can convert this const char* into char*?

Thank you.

like image 516
the_naive Avatar asked Apr 23 '12 13:04

the_naive


People also ask

How does strtok () work 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.

What is strtok ()?

Return Value The first time the strtok() function is called, it returns a pointer to the first token in string1. In later calls with the same token string, the strtok() function 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-ended.

What type does strtok return?

strtok() returns a NULL pointer. The token ends with the first character contained in the string pointed to by string2. If such a character is not found, the token ends at the terminating NULL character.


2 Answers

Since strtok actually writes to your string, you need to make a writable copy of it to tokenize;

char* copy = strdup(myReadonlyString);
...tokenize copy...
free(copy);
like image 119
Joachim Isaksson Avatar answered Sep 19 '22 01:09

Joachim Isaksson


Declare it as an array:

char tokenedStr[] = "OpenStack:OpenStack1";

if not possible, copy it to a char array.

like image 43
MByD Avatar answered Sep 22 '22 01:09

MByD