C/C++语言统计文件中单词出现个数

统计文件中单词个数,思前想后有了两种解决方案,记录一下,供自己和大家参考

例子

实验文件:c:\\1.txt

实现方案1:

#include <stdio.h>
#include <string.h>
int CountWordsOfEuropeanTxtFile(char *szFileName);
int CountWordsInOneLine(const char *szLine);
int main()
{
	char name[10]={"C:/1.txt"};
	printf("文件中单词个数%d\n",CountWordsOfEuropeanTxtFile(name));

	return 0;
}
/***********************************************\
函数名称:
	CountWordsOfEuropeanTxtFile
功能描述:
	统计文件中单词个数
函数参数:
	char *szFileName 文件名
返回值:
	int 词的个数
\**********************************************/
int CountWordsOfEuropeanTxtFile(char *szFileName)
{
	int nWords = 0;//词计数变量,初始值为0
	FILE *fp; //文件指针
	char carrBuffer[1024];//每行字符缓冲,每行最多1024个字符

	//打开文件
	if ((fp = fopen(szFileName,  "r")) == NULL)
	{
		return -1;	//文件打开不成功是返回-1
	}

	while (!feof(fp))//如果没有读到文件末尾 
	{
		//从文件中读一行
		if (fgets(carrBuffer, sizeof(carrBuffer),fp) != NULL)
			//统计每行词数
			nWords += CountWordsInOneLine(carrBuffer);
	}

	//关闭文件
	fclose(fp);

	return nWords;
}
/*
 *  函数名称:
 *		CountWordsInOneLine
 *	功能:统计一行正文中词的个数
 *	参数:const char *szLine 一行正文
 *	返回值:
 *	int 单词数
 */
int CountWordsInOneLine(const char *szLine)
{
	int nWords = 0;
	int i=0;
	for (;i<strlen(szLine);i++)
	{
		if (*(szLine+i)!=' ')
		{
			nWords++;
			while ((*(szLine+i)!=' ')&&(*(szLine+i)!='\0'))
			{
				i++;
			}
		}

	}
			printf("%d\t",nWords);
	
	return nWords;
}

实验方案2:

设置标志位,标志单词和空格之间的变化

#include <stdio.h>
#include <string.h>
int CountWordsOfEuropeanTxtFile(char *szFileName);
int CountWordsInOneLine(const char *szLine);
int main()
{
	char name[10]={"C:/1.txt"};
	printf("文件中单词个数%d\n",CountWordsOfEuropeanTxtFile(name));

	return 0;
}
/***********************************************\
函数名称:
	CountWordsOfEuropeanTxtFile
功能描述:
	统计文件中单词个数
函数参数:
	char *szFileName 文件名
返回值:
	int 词的个数
\**********************************************/
int CountWordsOfEuropeanTxtFile(char *szFileName)
{
	int nWords = 0;//词计数变量,初始值为0
	FILE *fp; //文件指针
	char carrBuffer[1024];//每行字符缓冲,每行最多1024个字符

	//打开文件
	if ((fp = fopen(szFileName,  "r")) == NULL)
	{
		return -1;	//文件打开不成功是返回-1
	}

	while (!feof(fp))//如果没有读到文件末尾 
	{
		//从文件中读一行
		if (fgets(carrBuffer, sizeof(carrBuffer),fp) != NULL)
			//统计每行词数
			nWords += CountWordsInOneLine(carrBuffer);
	}

	//关闭文件
	fclose(fp);

	return nWords;
}
/*
 *  函数名称:
 *		CountWordsInOneLine
 *	功能:统计一行正文中词的个数
 *	参数:const char *szLine 一行正文
 *	返回值:
 *	int 单词数
 */
int CountWordsInOneLine(const char *szLine)
{
	int nWords = 0;
	int i=0;
	int flag=0;
	for (;i<strlen(szLine);i++)
	{
		if (*(szLine+i)==' ')
		{
			flag=0;
		}
		else 
		{
			if (flag==0)
			{
				flag=1;
				nWords++;
			}
		}

	}
		
	
	return nWords;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值