How to use Strtok for tokenizing a Const char*?

我怕爱的太早我们不能终老 提交于 2019-12-20 18:15:55

问题


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.


回答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);



回答2:


Declare it as an array:

char tokenedStr[] = "OpenStack:OpenStack1";

if not possible, copy it to a char array.




回答3:


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.



来源:https://stackoverflow.com/questions/10281712/how-to-use-strtok-for-tokenizing-a-const-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!