简单的字符统计问题

chump345 2009-11-02 12:16:32
package Test;
import java.util.Scanner;

import java.io.*;

public class TestStat {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
String s = scanner.next();
System.out.println(s);
try{
File f = new File(s);
FileInputStream f1 = new FileInputStream(f);
DataInputStream in = new DataInputStream(f1);
int a;
int s1=0,n=1,w=0;
while((a=in.read())!=-1){
if(a==32){
s1++;
}else
if(a==13){
n++;
}else{
w++;
}
}
System.out.println(s1);
System.out.println(n);
System.out.println(w);
f1.close();
in.close();
}catch(IOException e){
System.out.println("文件读取失败!");
}
}

}


上面代码是我写的一个统计文件中空格s1,行n 字符w的数量`
问题是`
我每在代码中加一空行` n自加1` 但是w也自加1` 这是为什么呢`
原题本来是要统计单词的数量的`
但我觉得太麻烦了`就改成了统计字符`
统计单词有没有什么好的办法呢` 除了判断两个空格间是否有字符外`
...全文
74 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
gukuitian 2009-11-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gukuitian 的回复:]
全都读入String 中,然后用正则就行了。

\b\w*\b
[/Quote]

public static void main(String[] args)
{
String s="acs,bcd ad.ad";
Pattern p = Pattern.compile("\\b\\w*\\b");
Matcher m = p. matcher(s);
while (m.find())
{
//记数器++
System.out.println(m.group());

}
}
smallbear923 2009-11-02
  • 打赏
  • 举报
回复
是不是回车键也算是字符了。。
gukuitian 2009-11-02
  • 打赏
  • 举报
回复
全都读入String 中,然后用正则就行了。

\b\w*\b

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧