java字符统计


之前看到几个迅雷的上机题,于是在空闲之余写了一个简单的测试:(代码测试通过,如果需要应用到时间项目中需要对异常处理进行处理,也仅代表个人观点,仅供参考,欢迎大家提出更优解决方案)

// 统计文件中指定字符出现个数和位置以及在文件中的行数
BufferedReader in = null;
int count = 0;
int line = 0;
try{
File f = new File("E:\\ftp.txt");
in = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String readLine = null;
String searchStr = "java";
while((readLine = in.readLine()) != null){
++ line;
int position = readLine.indexOf(searchStr);
if(position != -1){
++ count;
System.out.println(readLine + "\t\t文件第 " + line + "行\t\t偏移量:" + position);
}
}
System.out.println("\n字符串出现次数:" + count);
}catch(FileNotFoundException e){

}catch(IOException ex){

}finally{
try{
if(in != null)
in.close();
}catch(Exception exx){}
}


// 统计文件中的字符、数字、空格、以及其它字符
int digit = 0;
int whiteSpace = 0;
int letter = 0;
int another = 0;
BufferedReader in = null;
try{
// DataInputStream in = new DataInputStream(new FileInputStream(new File("E:\\ftp.txt")));
in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\ftp.txt"))));
String readLine = null;
while((readLine = in.readLine()) != null){
// Character ch = new Character(c);
char c ;
for(int i=0;i<readLine.length();i++){
c = readLine.charAt(i);
if(Character.isDigit(c))
++ digit;
else if(Character.isLetter(c))
++ letter;
else if(Character.isWhitespace(c))
++ whiteSpace;
else
++ another;
}
}
System.out.println("数字个数:" + digit + "\n字符个数:" + letter + "\n空格个数:" + whiteSpace + "\n其它字符:" + another);
}catch(FileNotFoundException ex){
System.out.println("ex:" +ex.getMessage());
}catch(IOException e){
System.out.println("e:" + e.getMessage());
}finally{
try{
if(in != null)
in.close();
}catch(Exception exx){}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值