计算字符串中的单词数,C++

Mas*_*der 6 c++ string counting

可能重复:
C++函数计算字符串中的所有单词

所以我有一行单词,我用C++存储在一个字符串中.即"有一个名叫比利的农民\n"

我想知道字符串中的单词数量(即当前有6个单词).谁能告诉我怎么做?如果这是不可能的,有一种方法可以计算字符串中的空格数(即"").让我知道谢谢!

Die*_*ühl 9

当然,这很简单:

std::cout << "number of words: "
          << std::distance(std::istream_iterator<std::string>(
                               std::istringstream(str) >> std::ws),
                           std::istream_iterator<std::string>()) << '\n';
Run Code Online (Sandbox Code Playgroud)

只是为了一点解释:

  1. 读取std::string前导空格后读取单词,其中单词是非空白字符序列.
  2. std::istream_iterator<T>T通过读取相应的对象将输入流转换为对象序列,直到读取失败.
  3. std::istringstream将a std::string转换为正在读取的流.
  4. 构造函数参数std::istream_iterator<T>std::istream&,即临时std::istringstream不能直接使用,但需要获取引用.这是唯一有趣的效果std::ws,也跳过领先的空白.
  5. std::distance()确定序列中有多少元素(最初使用的std::count()元素确定序列中有多少元素与给定条件匹配,但实际上缺少了条件).


mau*_*uve 8

计算单词的一种简单方法是使用带有std :: string的>>运算符,如下所示:

std::stringstream is("There was a farmer named Billy");
std::string word;

int number_of_words = 0;
while (is >> word)
  number_of_words++;
Run Code Online (Sandbox Code Playgroud)

当从std :: istream中提取std :: string时,>> operator()将在其默认设置中跳过空格,这意味着它将为您提供由一个或多个空格分隔的每个"单词".因此,即使单词由多个空格分隔,上面的代码也会给出相同的结果.