c++ - 存储 strtok() token 的值?

标签 c++ arrays string pointers strtok

我想使用 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/

相关文章:

c++ - 根据模板类型在 std::to_string() 和 .toString() 之间切换

C++调用一个从txt文件输出信息的函数

c++ - 在 C++ 中避免 lambda 拷贝

c++ - boost asio 中的链接错误

c - 删除二叉堆中的最顶层元素

php - 从数组中删除重复项,保留一些值

java - BufferedReader 字符串内存泄漏?

c++ - SIGINT 处理和 getline

c++ - 如何创建一个Linux共享库,将所有二进制依赖项包含到一个so文件中?

java - 从数组中删除数字