c++ - 在C++中查找重复的单词数

标签 c++

有没有办法找出一个单词在文本中重复了多少次。

文本是字符数组(char[])

text = this is a book,and this book is about book.

word = book

result = 3

最佳答案

因为这显然是家庭作业,没有这样标记,所以我会给你一个解决方案,你显然不能作为作业提交,因为你的老师会知道你在互联网上得到它。

没有诸如忽略标点符号之类的要求,因此我允许自己编写一个仅适用于清晰分隔的单词的版本,因此在示例文本字符串中插入了空格。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>

    // Count clearly separated occurrences of `word` in `text`.
std::size_t count ( const std::string& text, const std::string& word )
{
    std::istringstream input(text);
    return (std::count(std::istream_iterator<std::string>(input),
        std::istream_iterator<std::string>(), word));
}

int main ( int, char ** )
{
    const char text[] = "this is a book , and this book is about book .";
    const char word[] = "book";
    std::cout << count(text, word) << std::endl;
}

输出:

3

关于c++ - 在C++中查找重复的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4197786/

相关文章:

c++ - C++ 内存调试器

c++ - C++尝试使用max和累加函数

c++ - SDL图像不显示

c++ - Long double 没有提供所需的精度

vector 的 C++ 段错误

c++ - 带有模板函数和 'using namespace' 的 VS2008(+?) 编译器错误

c++ - 如何知道某个指针是否已在其他地方释放

.net - 在混合模式 C++ 项目中从 CLR 到 SEH 异常获取敏感信息

c++ - 在递增整数索引时迭代容器的惯用方法是什么?

c++ - 我可以从 Visual Studio 即时窗口调用 Win32 API 吗?