存储 strtok() 代币的值
Storing value of strtok() tokens?
我想使用 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;
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- 在c++中获取两个大int,并将它们存储在数组中
- 存储 strtok() 代币的值