c++ - 拆分字符数组并存储到向量中
问题描述
我在网上搜索过,但找不到用空格(“”)拆分字符数组并将每个单词存储到向量中的方法。
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
}
解决方案
您可以使用以下简单的算法:
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
,它允许根本不复制字符串。
推荐阅读
- javascript - 有没有办法在定义之前调用 html 元素?
- variables - 全局变量只被调用一次然后就失去了作用域
- spring - Spring Security:无法重新登录
- apache-spark - 当我使用 C:\hadoop\bin\winutils.exe 运行 chmod 时,它显示“应用程序无法正确启动”
- python - Tensorflow 通用句子编码器中的 OpError
- python - Tensorflow dataset.map lambda自定义函数不适用于每张图像,仅适用于整个数据集
- reactjs - 如何在 React js web APP 中添加编辑器并将数据存储在 mongodb 中
- python - 我无法使用 pyinstaller 创建独立的 exe 文件,主脚本包含 Qprocess
- javascript - 如何将查询语法解析为具有分组和优先级的数据库查询?
- kubernetes - Pod 在创建时会消耗其请求或限制中指定的全部资源吗?