C++ 拆分字符数组并存储为向量
我在网上搜索过,但找不到按空格(“”)拆分字符数组并将每个单词存储到向量中的方法C++ 拆分字符数组并存储为向量,c++,char,tokenize,C++,Char,Tokenize,我在网上搜索过,但找不到按空格(“”)拆分字符数组并将每个单词存储到向量中的方法 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 cha
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
}
intmain()
{
字符串输入;
矢量输入;
getline(cin,输入);
char*chararray=新字符[input.length()+1];
strcpy_s(chararray,input.length()+1,input.c_str());
//按空格拆分字符并存储到splitInput中的代码
}
您可以使用以下简单算法:
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
的向量,它允许根本不复制字符串