How to use Strtok for tokenizing a Const char*?
Asked Answered
S

3

25

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.

Shelton answered 23/4, 2012 at 13:40 Comment(4)
Copy it? linux.die.net/man/3/strdupDoubledealing
Did you mean I should copy from that page?Shelton
No, I meant you should copy the string using the function described.Doubledealing
Yup, spot on.I did the same.ThanksShelton
T
25

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);
Telugu answered 23/4, 2012 at 13:43 Comment(2)
A c++ way of making a copy would be std::vector<char> copy(myReadonlyString, myReadonlyString+strlen(myReadonlyString));. You can then tokenize copy->data(). The compiler will de-allocate the copy automatically whenever it goes out of scope.Bronchiole
@Manuel, the value you've stored in copy isn't null-terminated. Use strlen(myReadonlyString) + 1 to ensure the input's terminator is included in the vector.Lumbard
C
2

Declare it as an array:

char tokenedStr[] = "OpenStack:OpenStack1";

if not possible, copy it to a char array.

Creedon answered 23/4, 2012 at 13:42 Comment(0)
G
0

You can make a copy of your non-modifiable string and then use strtok.

You can portably use malloc and strcpy to copy the string.

Gusto answered 23/4, 2012 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.