这里我试图将字符串标记复制到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*)
答案 0 :(得分:1)
在字符串上调用c_str:
word[i] = (const char *)strdup(t.c_str());
供参考: http://en.cppreference.com/w/cpp/string/basic_string/c_str
答案 1 :(得分:1)
这可能有所帮助:
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;
}
答案 2 :(得分:1)
“我的目的是将字符串文本中的每个单词都用char数组字[],每个单词转换为单词[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;
参见 HERE
答案 3 :(得分:1)
直接在这里传递词语:
std::ostringstream bfr;
word = strtok(& text[0]," ");
while (word!= NULL) {
printf("\n Word %s \n",word);
bfr << word << " ";
word = strtok(NULL, " ");
j++;
}
答案 4 :(得分:0)
这可能有所帮助!
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++;
}