存储 strtok() 代币的值

Storing value of strtok() tokens?

本文关键字:strtok 存储      更新时间:2023-10-16

我想使用 strtok() 函数来解析字符串,我想在返回的令牌中创建值的副本(因为我收集到从此函数返回的令牌是指针)。

从本质上讲,我的 AIM 是创建一个指向字符串数组的指针,该数组在每个标记的地址保存值的副本。到目前为止,我的代码尝试这样做(并且失败)如下:(我也希望令牌能够容纳足够的空间来容纳三个字符)。

(注意我对更改如何拆分字符串的方法不感兴趣 - 我知道 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++,只需使用向量来保存字符串:

  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;
  }

如果您需要从存储在向量中的字符串访问原始指针,只需执行s.c_str()

你不需要token变量。您的代码将words_split的每个元素设置为指向同一标记,该令牌最终将只是字符串中的最后一个标记。

只需存储strtok返回的地址:

int count = 0;
k = strtok(words, ",");
while (k) {
    words_split[count++] = k;
}

如果需要制作副本,可以使用strdup()功能:

    words_split[count++] = strdup(k);

这是一个 POSIX 函数,不是标准C++。如果需要,请参阅实现的 strdup 用法。

或者使用 std::string 而不是 C 字符串,就像 mnistic 的答案一样。

这基本上是 mnistic 答案的改头换面版本。添加以防万一可能会对您有所帮助。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    char sentence[] = "red, dry, wet, gut"; // this is the input string
    vector<char *> words;
    for(char *token=strtok(sentence,","); token != NULL; token=strtok(NULL, ","))
    {
        const int wordLength = strlen(token) + 1;
        char *word = new char [wordLength];
        strcpy(word, token);
        words.push_back(word);
        cout << "nWord = " << word;
    }

    // cleanup
    for(int i=0; i<words.size(); i++)
    {
        delete[] words[i];
    }
    return 0;
}