How to use Strtok for tokenizing a Const char*?
13,943
Solution 1
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);
Solution 2
Declare it as an array:
char tokenedStr[] = "OpenStack:OpenStack1";
if not possible, copy it to a char array.
Author by
the_naive
Updated on June 06, 2022Comments
-
the_naive about 2 years
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.
-
ManuelAtWork over 8 yearsA c++ way of making a copy would be
std::vector<char> copy(myReadonlyString, myReadonlyString+strlen(myReadonlyString));
. You can then tokenizecopy->data()
. The compiler will de-allocate the copy automatically whenever it goes out of scope. -
Rob Kennedy about 6 years@Manuel, the value you've stored in
copy
isn't null-terminated. Usestrlen(myReadonlyString) + 1
to ensure the input's terminator is included in the vector.