C char数组和向量字符串

C++ char array and vector string

本文关键字:向量 字符串 数组 char      更新时间:2023-10-16

我想将字符数组中的单词复制到vector字符串。我编写了以下代码,它给了我错误的错误,即字符串,vector,vector,vector,vector,vector,vector,vector,vector,vector,vector vector,vector vector,vector,vector,vector vector clast clast clast string n offer。我在标题文件中声明了该函数,您可以帮助您吗?

这是代码:

vector<string> split(char sentence[])
{
    vector<string> ans(100);
    int count=0;
    for(unsigned int i=0;i<sentence.size();i++)
    {
    if(sentence[i]==' ')
        count=count+1;
    ans[count]=ans[count]+sentence[i];
    }
    return ans;
}

a char[]是一种原始类型,没有成员函数,例如没有 .size() ...

的东西

您确定自己知道自己在做什么吗?这,丢失的标题(卢切安已经评论过)给人的印象,真的……

您需要包括标题<vector><string>,并将其与std::合格或使用using指令。全名资格应优先:

std::string
std::vector

编辑:我没有注意到char*::size错误,因为我专注于您发布的错误消息("在此范围中没有声明")。有人认为这值得一票...

您真的应该只使用内置库或其他东西,然后用正则表达式拆分字符串。

而不是使用char[]使用string。它很容易将char[]转换为此,它可能是一个字符串,因此您应该更早地将其切出。

要组成您的vector<string>,您要做的就是:

#include <regex.h>
#include <string.h>
#include <vector.h>
using namespace std;
vector<string> split(string s){
    regex r ("\w+"); //regex matches whole words, (greedy, so no fragment words)
    regex_iterator<string::iterator> rit ( s.begin(), s.end(), r );
    regex_iterator<string::iterator> rend; //iterators to iterate thru words
    vector<string> result<regex_iterator>(rit, rend);
    return result;  //iterates through the matches to fill the vector
}

可能需要解决一个或两个错误(我只是有点生锈),并且也可以使用内联语句被大大压实。

记住:C 的魔法有两种形式:迭代器和内联语句。