首页 > 解决方案 > 拆分字符数组并存储到向量中

问题描述

我在网上搜索过,但找不到用空格(“”)拆分字符数组并将每个单词存储到向量中的方法。

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++chartokenize

解决方案


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

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,它允许根本不复制字符串。


推荐阅读