C++统计文章中单词出现的个数和每个字母出现的次数并按字母顺序排序

C++统计文章中单词出现的个数和每个字母出现的次数并按字母顺序排序


在主函数中进行循环写法

利用array数组和数字与字符的转换进行编程,如下:
效果如下:

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include<vector>
#include<string>
#include<fstream>
#include<cstdlib>

using namespace std;


int main() {

	ifstream  f;
	f.open("C:\\Users\\Administrator\\source\\repos\\test2.txt");
	if (f.fail()) {
		cout << "input file failed.\n";
		exit(1);
	}

	 string s;
	getline(f, s);

	
	
	int num[26];
	int word_count = 0;
	for (int i = 0; i < 26; i++) {
		num[i] = 0;

	}
	for (int i = 0; i < s.length(); i++) {
		cout << s[i];
		if (isalpha(s[i])) {
			s[i] = tolower(s[i]);//大写字母全变为小写字母
			int num_count = int(s[i]) - 97;
			num[num_count] = num[num_count] + 1;//每个字母出现啊的次数计数
		}
		
		else if (s[i] == ' ') {
			word_count=word_count+1;//每个单词出现的次数计数

		}
		else {
			continue;
		}
	}
	word_count++;//因为是计算空格,所以最后要加1
	cout <<'\n' <<endl;
	cout << word_count << '\t' << "words" << endl;

	for (int j = 0; j < 26; j++) {
		if (num[j] > 0) {
			char word_now;
			word_now= (char)(j + int('a'));//依据位置,转为为字母序
			cout << num[j]  << '\t' << word_now << endl;

		}
	}

	
	
	

}

封装成函数

计算单词个数,统计词频并输出

void word_count(string s) {
	int num[26];
	int word_count = 0;
	for (int i = 0; i < 26; i++) {
		num[i] = 0;

	}
	for (int i = 0; i < s.length(); i++) {
		cout << s[i];
		if (isalpha(s[i])) {
			s[i] = tolower(s[i]);//大写字母全变为小写字母
			int num_count = int(s[i]) - 97;
			num[num_count] = num[num_count] + 1;//每个字母出现啊的次数计数
		}

		else if (s[i] == ' ') {
			word_count = word_count + 1;//每个单词出现的次数计数

		}
		else {
			continue;
		}


		
	}
	word_count++;//因为是计算空格,所以最后要加1
	cout << '\n' << endl;
	cout << word_count << '\t' << "words" << endl;


	for (int j = 0; j < 26; j++) {
		if (num[j] > 0) {
			char word_now;
			word_now = (char)(j + int('a'));//依据位置,转为为字母序
			cout << num[j] << '\t' << word_now << endl;

		}
	}

}

主函数更改文件

int main() {

	ifstream  f;
	f.open("C:\\Users\\Administrator\\source\\repos\\English.txt");
	if (f.fail()) {
		cout << "input file failed.\n";
		exit(1);
	}

	 string s;
	getline(f, s);

	
	
	word_count(s);

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值