首页 > 解决方案 > 函数将每个单词与字符串分开并将它们放入向量中,而不使用 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);
    }
}

标签: c++

解决方案


你知道怎么读“单词”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>());
}

推荐阅读