0

I've searched online but can't find a way to way to split a char array by space (" ") and store each word into a vector.

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

}

1 Answers1

0

You can use the following, simply algorithm:

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

A more advanced approach is to create a vector of std::string_view, which allows to not copy the strings at all.

eerorika
  • 232,697
  • 12
  • 197
  • 326