【问题标题】:Splitting char array and storing into vector [duplicate]拆分char数组并存储到向量中[重复]
【发布时间】:2019-12-02 18:48:17
【问题描述】:

我在网上搜索过,但找不到一种方法来按空格 (" ") 拆分 char 数组并将每个单词存储到一个向量中。

int main()
{
string input;
vector <string> splitInput;

getline(cin, input);

char* chararray = new char[input.length() + 1]; 
strcpy_s(chararray, input.length() + 1, input.c_str());

//code to split chararray by space and store into splitInput

}

【问题讨论】:

    标签: c++ char tokenize


    【解决方案1】:

    您可以使用以下简单的算法:

    let temp be an empty string
    for each index i in input string s:
        if s[i] is space then
            add temp into result vector
            clear temp
        else
            add s[i] into temp
     if temp is not empty then
         add temp into result vector
    

    一种更高级的方法是创建一个std::string_view 的向量,它允许根本不复制字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多