计算字符串中的单词数,C++
Counting the number of words in a string, C++
可能的重复项:
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';
只是为了解释一下:
- 读取
std::string
在跳过前导空格后读取单词,其中单词是一系列非空格字符。 -
std::istream_iterator<T>
通过读取相应的对象将输入流转换为T
对象的序列,直到读取失败。 -
std::istringstream
获取std::string
并将其转换为正在读取的流。 std::istream_iterator<T>
的构造函数参数是std::istream&
的,即临时std::istringstream
不能直接使用,但需要获取引用。这是std::ws
唯一有趣的效果,它也跳过了前导空格。-
std::distance()
确定序列中有多少个元素(最初使用的std::count()
确定序列中有多少元素与给定条件匹配,但条件实际上缺失)。
相关文章:
- QTreeView幻灯片多选后无法使用单击选择
- 为什么在单例中,检查类==空?
- C++ 实现模板单例类时出现链接错误
- OOP 中的单成员指针
- 在类中存储单例的指针
- QMouseEvent 用于单机芯
- 如何打印以特定字符开头的单词数?
- 将输入作为C 中的单词数组
- 阅读一个大文件来计算重复K次的单词数
- C++ 查找其中字母最少的单词数
- 我的逻辑有什么问题?尝试计算文件中包含特定字符的单词数
- 我需要在接受用户输入后返回 c 刺痛中的单词数
- 计算字符串中的单词数,C++
- 如何输入单词数组c++
- 计算字符数组C++中的单词数
- c++计算一行中的单词数
- 如何通过检查v. dictionary来查找一个短语中删除空格的单词数
- 函数定义计算单词数
- 如何在列表中找到单词数
- 如何获得字符串中的单词数