14.81 列出特定长度单词的个数

本文介绍了一种使用C++编程语言统计文件中单词长度的方法,通过自定义函数检查字符串长度,并统计不同长度单词的数量。此外,还展示了如何统计超过特定长度的单词数,如超过10个字符的单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class check_length{
public:
    check_length(size_t size) : length(size) {}
    bool operator()(const std::string &s) {
        return s.size() == length;
    }
private:
    size_t length;
};

int main(int argc, char **argv) {
    ifstream f(argv[1]);
    if (f) {
        string ret;
        vector<string> v;
        while (f >> ret) {
            v.push_back(ret);
        }
        vector<int> record(10);
        for (size_t i = 0; i < 10; ++i) {
            record[i] = count_if(v.begin(), v.end(), check_length(i+1));
        }
        cout << "list the word length" << endl;
        for (const auto &i:record) {
            cout << record[i] << endl;
        }
    } else {
        exit(1);
    }
}

longer and shorter:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class check_length{
public:
    check_length(size_t size) : length(size) {}
    bool operator()(const std::string &s) {
        return s.size() == length;
    }
private:
    size_t length;
};

class longer_than{
public:
    longer_than(size_t size) : length(size) {}
    bool operator()(const std::string &s) {
        return s.size() > length;
    }
private:
    size_t length;
};

class shorter_than{
public:
    shorter_than(size_t size) : length(size) {}
    bool operator()(const std::string &s) {
        return s.size() <= length;
    }
private:
    size_t length;
};

int main(int argc, char **argv) {
    ifstream f(argv[1]);
    if (f) {
        string ret;
        vector<string> v;
        while (f >> ret) {
            v.push_back(ret);
        }
        size_t numbers = count_if(v.begin(), v.end(), longer_than(10));
        cout << "longer than 10 words " << numbers << endl;
    } else {
        exit(1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值