c++ - 函数将每个单词与字符串分开并将它们放入向量中,而不使用 auto 关键字?
问题描述
我真的被困在这里了。所以我不能编辑主函数,里面有一个函数调用,唯一的参数是字符串。如何使此函数将字符串中的每个单词放入向量中,而不使用 auto 关键字?我意识到这段代码可能真的是错误的,但它应该是我最好的尝试。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> extract_words(const char * sentence[])
{
string word = "";
vector<string> list;
for (int i = 0; i < sentence.size(); ++i)
{
while (sentence[i] != ' ')
{
word = word + sentence[i];
}
list.push_back(word);
}
}
int main()
{
sentence = "Help me please" /*In the actual code a function call is here that gets input sentence.*/
if (sentence.length() > 0)
{
words = extract_words(sentence);
}
}
解决方案
你知道怎么读“单词”std::cin
吗?
然后,您可以将该字符串放入 astd::istringstream
中,它的作用类似于std::cin
“读取”字符串。
在循环中使用流提取运算符>>
,将所有单词一一获取,并将它们添加到向量中。
也许是这样的:
std::vector<std::string> get_all_words(std::string const& string)
{
std::vector<std::string> words;
std::istringstream in(string);
std::string word;
while (in >> word)
{
words.push_back(word);
}
return words;
}
通过对 C++ 及其标准类和函数有更多了解,您实际上可以使函数更短:
std::vector<std::string> get_all_words(std::string const& string)
{
std::istringstream in(string);
return std::vector<std::string>(std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>());
}
推荐阅读
- azure-data-explorer - KQL - Include Time zone in the Kusto Query
- laravel - 错误 api post vue laravel
- powerbi - 瀑布图 - Power Bi
- apple-push-notifications - APNS 内容可用推送在 iOS 15 中不起作用
- c# - StreamReader ReadLineAsync 忽略回车并挂起
- javascript - 装饰 textarea 后 CodeMirror 样式不起作用
- android - 你能给我一些示例代码来证明永远不要依赖于执行可组合函数的副作用吗?
- javascript - 如何使用 ffmpeg 模块修剪 youtube 视频?
- typescript - 具有默认参数的函数的 JS Doc
- javascript - 有没有办法将值动态添加到 onclick 函数?