首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字符向量中单词出现次数的计数

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

Stack Overflow用户
提问于 2015-05-01 16:37:31
回答 3查看 1.4K关注 0票数 1

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

代码语言:javascript
复制
#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我只能计数字符数。如何计算字符向量中“用户”出现的次数?

例如,text.txt

代码语言:javascript
复制
USERABRUSER#$$* 34 USER ABC RR IERUSER

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-05-01 17:07:50

std::string有一个find成员函数,它可以在另一个字符串中找到一个字符串。您可以使用它来计数发生的事件,如下所示:

代码语言:javascript
复制
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;
}

例如:

代码语言:javascript
复制
int main() {
    std::string input{ "USERABRUSER#$$* 34 USER ABC RR IERUSER" };

    std::cout << count(input, "USER");
}

...produces是4的输出.

票数 3
EN

Stack Overflow用户

发布于 2015-05-01 16:53:08

我就是这样做的:

代码语言:javascript
复制
#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
EN

Stack Overflow用户

发布于 2015-05-01 17:04:25

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

代码语言:javascript
复制
#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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29991079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档