【问题标题】:Storing value of strtok() tokens?存储 strtok() 令牌的价值?
【发布时间】:2017-10-27 18:31:23
【问题描述】:

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

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

(注意,我对更改拆分字符串的方法不感兴趣 - 我知道 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 访问每个单独的元素,即红色。

【问题讨论】:

  • 最好不要使用strtok()在c++中分割字符串。
  • 至于你的问题:你需要使用strncpy()来复制token值。
  • @user0042 是的,我知道这可能不是最好的方法。你能解释一下我将如何使用 strncpy() 吗?就像我将它放在代码中的哪个位置一样?
  • @user0042 我想我理解这个函数是如何工作的,但我真的很困惑它与指针的关系——以及将它放在代码中的什么位置?比如,while 循环后半部分的内容是否正确?

标签: c++ arrays string pointers strtok


【解决方案1】:

由于您使用的是 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()

【讨论】:

    【解决方案2】:

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

    只存储strtok返回的地址:

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

    如果需要复制,可以使用strdup()函数:

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

    这是一个 POSIX 函数,而不是标准 C++。如果需要,请参阅 usage of strdup 以获取实现。

    或者使用 std::string 代替 C 字符串,如 mnistic 的回答。

    【讨论】:

      【解决方案3】:

      这基本上是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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-17
        • 2018-08-21
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2014-09-19
        相关资源
        最近更新 更多