有没有办法找出一个单词在文本中重复了多少次。
文本是字符数组(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/