我想使用 strtok() 函数来解析一个字符串,并且我想在返回的标记中创建值的拷贝(因为我了解到从该函数返回的标记是指针)。
本质上,我的目标是创建一个指向字符串数组的指针,该数组在每个标记的地址处保存值的拷贝。到目前为止,我尝试这样做(但失败了)的代码如下:(我还希望 token 能够容纳三个字符的足够空间)。
(注意,我对更改拆分字符串的方法不感兴趣——而且我知道 strtok 有缺点)
char words[] = "red, dry, wet, gut"; // this is the input string
char* words_split[100];
char token[3]; // creates space for a token to hold up to 3 characters (?)
int count = 0;
char* k = strtok(words, ","); // the naming of k here is arbitrary
while (k != NULL) {
k = strtok(NULL, ",");
token[0] = *k; // I'm aware the 0 here is wrong, but I don't know what it should be
words_split[count] = token;
count++;
}
然后我希望能够从 words_split 访问每个单独的元素,即红色。
最佳答案
由于您使用的是 C++,因此只需使用 vector 来保存字符串:
char words[] = "red, dry, wet, gut"; // this is the input string
std::vector<std::string> strs;
char* k;
for (k = strtok(words, " ,"); k != NULL; k = strtok(NULL, " ,")) {
strs.push_back(k);
}
for(auto s : strs)
{
std::cout << s << std::endl;
}
如果您需要从存储在 vector 中的字符串访问原始指针,只需执行 s.c_str()
。
关于c++ - 存储 strtok() token 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46981381/