分割char数组并存储到向量中

问题描述 投票:0回答:1

我已经在网上搜索过,但是找不到一种方法来通过空格(“”)分割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个回答
0
投票

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

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的向量,该向量根本不复制字符串。

© www.soinside.com 2019 - 2024. All rights reserved.