程序读取特定目录下的字符数
2015-10-31 13:17
330 查看
1、C语言实现:
这个Demo仅仅适用于对英文字母的统计,而不能对汉字进行统计,原因就是汉字的编码格式问题,下面是代码:
下面是程序运行的结果:
2、Java代码实现此功能:
其中使用到的工具类在下面:
好了,就是这些了,欢迎广大博友不断补充,旨在共同进步!
这个Demo仅仅适用于对英文字母的统计,而不能对汉字进行统计,原因就是汉字的编码格式问题,下面是代码:
#include <stdio.h> int main() { char fname[80];/*存贮文件名*/ FILE *rfp; long count;/*文件字符计数器*/ printf("Please input the file's name:\n"); scanf("%s",fname); if((rfp=fopen(fname,"r"))==NULL) { printf("Can't open file %s.\n",fname); exit(1); } count=0; while(fgetc(rfp)!=EOF) count++; fclose(rfp);/*关闭文件*/ printf("There are %ld characters in file %s.\n",count,fname); puts("\n Press any key to quit..."); getch(); return 0; }
下面是程序运行的结果:
2、Java代码实现此功能:
StringBuffer sb = new StringBuffer(); String length = ""; String fileTitle; String fileContent; try { BufferedReader reader = new BufferedReader(new FileReader( "F://test.txt")); while ((length = reader.readLine()) != null) { sb.append(length); } fileContent = sb.toString(); new Total().find(fileContent); String flag = "数据信息统计结果如下:" + "\n" + "汉字数目:"; flag += new Total().chineseCount; flag += "\n英文字母个数:"; flag += new Total().englishCount; flag += "\n特殊字符个数:"; flag += new Total().numberCount; flag += "\n总的字符个数为:" + (new Total().chineseCount + new Total().englishCount + new Total().numberCount); taShow.setText(flag); new Total().chineseCount = 0; new Total().englishCount = 0; new Total().numberCount = 0; } catch (Exception ec) { ec.printStackTrace(); } }
其中使用到的工具类在下面:
package Editer; /** * 分别统计出其中字符串中汉字,英文字母,数字,其他字符数量 * @author wWX154783 * */ public class Total { static String E1,E2,E3; String str="a12中国3@b&4语*言3c"; static int chineseCount = 0; static int englishCount = 0; static int numberCount = 0; public void find(String str) { String E1 = "[\u4e00-\u9fa5]";// 中文 String E2 = "[a-zA-Z]";// 英文 String E3 = "[0-9]";// 数字 String temp; for (int i = 0; i < str.length(); i++) { temp = String.valueOf(str.charAt(i)); if (temp.matches(E1)) { chineseCount++; } if (temp.matches(E2)) { englishCount++; } if (temp.matches(E3)) { numberCount++; } } System.out.println("汉字数:" + chineseCount); System.out.println("英文数:" + englishCount); System.out.println("数字数:" + numberCount); System.out.println("特殊字符:" + (str.length() - (chineseCount + englishCount + numberCount))); } }
好了,就是这些了,欢迎广大博友不断补充,旨在共同进步!
相关文章推荐
- 共用体(联合体)简介及在大小端判断的巧妙运用
- 程序读取特定目录下的字符数
- Machine Learning Algorithms Study Notes(5)—Reinforcement Learning
- 牛逼的架构 vs ‘牛逼’ 的人生
- 图学java基础篇之集合工具
- coderforce A. Case of the Zeros and Ones
- LeetCode(155) Min Stack
- cocos2dx 苹果5分辨率 适配错误
- [转]SQL注入攻防入门详解
- LeetCode(155) Min Stack
- 读《中国文学史》
- solr4.7中文分词器(ik-analyzer)配置
- 图学java基础篇之集合工具
- 64位Win7系统中配置Apache+Mysql+PHP环境
- xutils dbutils使用中遇到的问题
- level改bake
- [转]面向程序员的数据库访问性能优化法则
- 04OC之分类Category,协议Protocol,Copy,代码块block
- 简单几何(直线与线段相交) POJ 1039 Pipe
- Solr 连接数据库