1、C语言实现:
这个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)));
}
}
好了,就是这些了,欢迎广大博友不断补充,旨在共同进步!