C++ 统计文本中所有字符串出现次数

#include <iostream>
#include <string>
#include <fstream>
#include<sstream>
#include <map>

#include <algorithm>
#include <vector>

using namespace std;

int main()
{
	fstream infile;

	map<string, int>Maps;
	infile.open("words.txt");   //将文件流对象与文件连接起来 

	if (!infile.is_open())
	{
		cout << "open file error" << endl;
		return 0;
	}//若失败,则输出错误消息,并终止程序运行 

	string strfile, tmp;

	while (getline(infile, tmp))
	{
		strfile.append(tmp);
		strfile.append(" ");//一定要加这一行!!!因为getline是直接读取文本文件的一行,遇    //到回车换行符作为读取一行的结束,如果有如下情况:
                                     //abc bcf
                                     //a  如果读完一行不加空格那么读取完abc bcf后再读取a,//则bcfa为一个字符串,算作一个了
		tmp.clear();
	}

	for (int i = 0; i<strfile.length(); i++)
	{
		if (ispunct(strfile[i]))
			strfile[i] = ' ';
	}


	stringstream ss(strfile);
	while (ss >> tmp)
	{
		if (Maps.find(tmp) == Maps.end())
		{
			Maps.insert(pair<string, int>(tmp, 1));
		}
		else
		{
			Maps[tmp]++;
		}
	}

	for (map<string, int>::iterator it = Maps.begin(); it != Maps.end(); it++)
	{
		cout << it->first << it->second << endl;
	}

	infile.close();             //关闭文件输入流  

	system("pause");
	return 0;
}

抄的别人的:https://blog.csdn.net/FX677588/article/details/72643302

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值