【问题标题】:Counting the number of words in a string, C++ [duplicate]计算字符串中的单词数,C++ [重复]
【发布时间】:2012-10-04 05:44:33
【问题描述】:

可能重复:
C++ function to count all the words in a string

所以我有一行单词,我使用 C++ 将其存储在字符串中。即“有一个农民叫比利\n”

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

【问题讨论】:

  • @KirilKirov 是的,我确实想知道是否有任何内置函数可以执行此操作。什么都没找到
  • 你对“单词”的定义是什么?你能用正则表达式吗?
  • 像“farmer”或“Billy”这样的词
  • +1 到 wiso。一旦您将任何非 alpha 字符悬挂在一个或多个空格上方,下面的所有流提取解决方案都会落在他们的脸上。通过使用 isalpha() 检查第一个字符很容易修复,(好吧,无论如何更接近,但仍然如此)。这就是 OP 必须处理的全部内容吗?

标签: c++ string counting


【解决方案1】:

当然,很简单:

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&lt;T&gt; 通过读取对应的对象直到读取失败,将输入流变成T 对象的序列。
  3. std::istringstream 接受 std::string 并将其转换为正在读取的流。
  4. std::istream_iterator&lt;T&gt;的构造函数参数为std::istream&amp;,即临时的std::istringstream不能直接使用,需要获取引用。这是 std::ws 唯一有趣的效果,它也跳过了前导空格。
  5. std::distance() 确定序列中有多少元素(最初使用的std::count() 确定序列中有多少元素匹配给定条件,但实际上缺少条件)。

【讨论】:

  • :D 这对初学者来说并不简单,但是+1,我喜欢它。
  • 你能再解释一下吗?
  • 这不应该是 std::distance() 吗?
  • @mauve:好点:应该是std::distance() 而不是std::count()。我会修复代码。
【解决方案2】:

计算单词的一种简单方法是使用带有 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() 将在其默认设置中跳过空格,这意味着它将为您提供由一个或多个空格分隔的每个“单词”。所以即使单词被多个空格隔开,上面的代码也会给你同样的结果。

【讨论】:

  • 这样的东西太慢了。
  • @KirilKirov:是的,它非常慢,但它只需要几行代码就可以满足要求:)
  • 没错,这就是我没有投反对票的原因:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
相关资源
最近更新 更多