计算字符向量中单词的出现次数

Counting occurrences of word in vector of characters

本文关键字:单词 字符 向量 计算      更新时间:2023-10-16

我写了一个程序来存储字符向量中的文本文件。

#include<iostream>
#include<fstream>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
    vector<char> vec;
    ifstream file("text.txt");
    if(!file.eof() && !file.fail())
    {
        file.seekg(0, std::ios_base::end);
        std::streampos fileSize = file.tellg();
        vec.resize(fileSize);
        file.seekg(0, std::ios_base::beg);
        file.read(&vec[0], fileSize);
    }
    int c = count(vec.begin(), vec.end(), 'U');
    cout << c;
    return 0;
}

我想计算文本文件中"USER"的出现次数,但是使用计数我只能计算字符数。如何计算字符向量中"USER"的出现次数?

例如文本.txt

USERABRUSER#$$* 34 USER ABC RR IERUSER

那么"用户"的计数是4。单词只能是大写的。

std::string有一个find成员函数,该函数将查找一个字符串在另一个字符串中的出现。您可以使用它来计算发生次数,如下所示:

size_t count(std::string const &haystack, std::string const &needle) {
    auto occurrences = 0;
    auto len = needle.size();
    auto pos = 0;
    while (std::string::npos != (pos = haystack.find(needle, pos))) {
        ++occurrences;
        pos += len;
    }
    return occurrences;
}

例如:

int main() {
    std::string input{ "USERABRUSER#$$* 34 USER ABC RR IERUSER" };
    std::cout << count(input, "USER");
}

。产生 4 的输出。

这就是我会这样做的:

#include <fstream>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
   unordered_map<string, size_t> data;
   string line;
   ifstream file("text.txt");
   while (getline(file, line)) {
      istringstream is(line);
      string word;
      while (is >> word) {
        ++data[word];
      }
   }
   cout << data["USER"] << endl;
   return 0;
}

让我们再试一次。再一次,向量不是必需的。这就是我认为最C++惯用的方式。它使用std::stringfind()方法按顺序重复查找子字符串,直到到达字符串的末尾。

#include <fstream>
#include <iostream>
#include <string>
int main() {
    // Read entire file into a single string.
    std::ifstream file_stream("text.txt");
    std::string file_contents(std::istreambuf_iterator<char>(file_stream),
        std::istreambuf_iterator<char>());
    unsigned count = 0;
    std::string substr = "USER";
    for (size_t i = file_contents.find(substr); i != std::string::npos;
        i = str.find(substr, i + substr.length())) {
        ++count;
    }
}