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

来源:互联网 发布:空间站软件下载 编辑:程序博客网 时间:2024/05/21 15:32

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

例子

实验文件: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;//词计数变量,初始值为0FILE *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;//词计数变量,初始值为0FILE *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;}




0 0
原创粉丝点击