如何将字符串标记复制到字符 */字符数组
How to duplicate string token to char */char array
在这里,我试图将字符串tocken复制到char指针,如下所示:
#include <iostream>
#include <cstring>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int, char**)
{
string text = "token test string";
char *word;
char_separator<char> sep(" ");
tokenizer<char_separator<char>> tokens(text, sep);
int i=0;
for (const auto& t : tokens) {
cout << t << "." << endl;
word[i] =(const char *)strdup(t); // Error
i++; } }
错误是:test.cpp:18:40: error: cannot convert ‘const std::basic_string<char>’ to ‘const char*’ for argument ‘1’ to ‘char* strdup(const char*)
直接在这里传递单词:
std::ostringstream bfr;
word = strtok(& text[0]," ");
while (word!= NULL) {
printf("n Word %s n",word);
bfr << word << " ";
word = strtok(NULL, " ");
j++;
}
这可能会有所帮助:
int main()
{
string text = "token test string";
char_separator<char> sep(" ");
tokenizer<char_separator<char>> tokens(text, sep);
std::vector<std::string> > words;
for (const auto& t : tokens) {
cout << t << "." << endl;
words.push_back(t);
}
return 0;
}
在字符串上调用c_str:
word[i] = (const char *)strdup(t.c_str());
供参考:http://en.cppreference.com/w/cpp/string/basic_string/c_str
"我的目的是将字符串文本的每个单词都放在 char 数组 word[]中,每个单词都变成单词 [0] 到单词 [last]。然后我想将单词作为参数传递到某个函数中"
你可以做这样的事情:
std::istringstream iss(text);
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(strs));
char **word = new char*[strs.size()];
for(size_t i=0;i<strs.size();++i)
{
word[i] = new char[strs[i].size()+1];
strcpy(word[i],strs[i].c_str());
}
/* Clean up*/
for(size_t i = 0; i < strs.size(); ++i) {
delete [] word[i];
}
delete [] word;
看这里
这可能会有所帮助!
word = strtok(& text[0]," ");
while (word!= NULL) {
printf("n Word %s n",word);
// ch[i] = strdup(word);
strcpy(ch[i],word);
excluded_string[j]= strdup(word);
skp = BoyerMoore_skip(word, strlen(word) );
if(skp != NULL)
{
i++;
continue;
}
bfr << excluded_string[j] << " ";
result_string = bfr.str();
j++;
}
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?