c++ - 从句子中获取单词并将它们存储在字符串 vector 中

标签 c++

好的,伙计们......

这是包含所有字母的我的集合。我将一个词定义为由集合中的连续字母组成。

const char LETTERS_ARR[] = {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
const std::set<char> LETTERS_SET(LETTERS_ARR, LETTERS_ARR + sizeof(LETTERS_ARR)/sizeof(char));

我希望这个函数接受一个表示句子的字符串并返回一个字符串 vector ,该 vector 是句子中的各个单词。

std::vector<std::string> get_sntnc_wrds(std::string S) { 
    std::vector<std::string> retvec;
    std::string::iterator it = S.begin(); 
    while (it != S.end()) { 
        if (LETTERS_SET.count(*it) == 1) { 
            std::string str(1,*it);
            int k(0);
            while (((it+k+1) != S.end()) && (LETTERS_SET.count(*(it+k+1) == 1))) { 
                str.push_back(*(it + (++k)));
            }
            retvec.push_back(str);
            it += k;
        }
        else { 
            ++it;
        }
    }
    return retvec;
} 

例如,以下调用应返回字符串“Yo”、“dawg”等的 vector 。

std::string mystring("Yo, dawg, I heard you life functions, so we put a function inside your function so you can derive while you derive.");
std::vector<std::string> mystringvec = get_sntnc_wrds(mystring);

但一切都没有按计划进行。我尝试运行我的代码,它将整个句子放入 vector 的第一个也是唯一一个元素中。我的函数代码很乱,也许你能帮我想出一个更简单的版本。我不希望您能够在我编写该函数的可怜尝试中追踪我的思维过程。

最佳答案

试试这个:

#include <vector>
#include <cctype>
#include <string>
#include <algorithm>

// true if the argument is whitespace, false otherwise
bool space(char c)
{
  return isspace(c);
}

// false if the argument is whitespace, true otherwise
bool not_space(char c)
{
  return !isspace(c);
}

vector<string> split(const string& str)
{
  typedef string::const_iterator iter;
  vector<string> ret;
  iter i = str.begin();

  while (i != str.end()) 
  {
    // ignore leading blanks
    i = find_if(i, str.end(), not_space);
    // find end of next word
    iter j = find_if(i, str.end(), space);
    // copy the characters in [i, j)
    if (i != str.end())
      ret.push_back(string(i, j));
    i = j;
  }
  return ret;
}

split 函数将返回 stringvector,每个元素包含一个单词。

此代码取自 Accelerated C++书,所以它不是我的,但它有效。本书中还有其他使用容器和算法解决日常问题的绝佳示例。我什至可以用一行代码在输出控制台上显示文件的内容。强烈推荐。

关于c++ - 从句子中获取单词并将它们存储在字符串 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20113782/

相关文章:

c++ - 如何将 switch-case 语句更改为 if-else 语句

c++ - 函数重载变得模棱两可

c++ - 根据第一个选项选择选项组

c++ - 为什么指向函数的指针不能绑定(bind)到左值引用,而函数可以?

c++ - 按字符循环遍历 std 字符串的段错误

c++ - 了解循环C++中的循环

c++ - 将字符串转换为 GUID 的算法

c++ - boost::filesystem::rename:当文件已经存在时无法创建文件

c++ - 如何对派生类进行限制?

c++ - 在 C++ 中组合不同的文本文件