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

Counting the number of words in a string, C++

本文关键字:C++ 单词数 字符串 计算      更新时间:2023-10-16

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

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

我想知道字符串中的单词数(即目前有 6 个单词)。谁能告诉我怎么做?如果这是不可能的,有没有办法计算字符串中的空格数(即" ")。让我知道谢谢!

计算单词数的一种简单方法是将>> 运算符与 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++;

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

当然,这很简单:

std::cout << "number of words: "
          << std::distance(std::istream_iterator<std::string>(
                               std::istringstream(str) >> std::ws),
                           std::istream_iterator<std::string>()) << 'n';

只是为了解释一下:

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