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

时间:2015-05-01 16:37:31

标签: c++

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

#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”的出现次数,但是使用count我只能计算字符数。如何计算字符向量中“USER”的出现次数?

例如 text.txt

USERABRUSER#$$* 34 USER ABC RR IERUSER

然后“USER”的计数为4.单词只能是大写。

3 个答案:

答案 0 :(得分:3)

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的输出。

答案 1 :(得分:2)

我就是这样做的:

#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;
}

答案 2 :(得分:0)

我们再试一次。再一次,矢量不是必需的。这就是我认为最常用的C ++惯用方法。它使用std::string的{​​{1}}方法按顺序重复查找子字符串,直到到达字符串的末尾。

find()
相关问题