如何将字符串标记复制到字符 */字符数组

How to duplicate string token to char */char array

本文关键字:字符 数组 复制 字符串      更新时间:2023-10-16

在这里,我试图将字符串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++; 
        }