统计字符串str中小写字母,大写字母,数字的个数Matcher match = Pattern.compile("[a-z]").matcher(str); while (match.find()) lCount++; match = Pattern.compile("[A-Z]").matcher(str); while (match.find()) uCount++; match = Pattern.compile("\\d").matcher(str); while (match.find()) nCount++;
String fileName = "D:" + File.separator + "hello.txt"; File file = new File(fileName); Reader reader = new InputStreamReader(new FileInputStream(file)); int temp = 0; String s = ""; while ((temp = reader.read()) != -1) { s += (char)temp; } reader.close(); System.out.println(s.length());//char长度 System.out.println(s);
java中一个char是两个字节读入的时候统计下byte,是不是就可以得到char数
这样你还不如用StringBuffer... 话说文件要是很大,你这不是会挂掉
自己统计一下就可以了 for example BufferedReader br = new BufferedReader(new FileReader("xxx")); int count = 0, read = 0; while ((read=br.read()) != -1) { count++; } br.close(); System.out.printf("char count = %d\n", count);
统计字符串str中小写字母,大写字母,数字的个数Matcher match = Pattern.compile("[a-z]").matcher(str);
while (match.find())
lCount++;
match = Pattern.compile("[A-Z]").matcher(str);
while (match.find())
uCount++;
match = Pattern.compile("\\d").matcher(str);
while (match.find())
nCount++;
String fileName = "D:" + File.separator + "hello.txt";
File file = new File(fileName);
Reader reader = new InputStreamReader(new FileInputStream(file));
int temp = 0;
String s = "";
while ((temp = reader.read()) != -1) {
s += (char)temp;
}
reader.close();
System.out.println(s.length());//char长度
System.out.println(s);
话说文件要是很大,你这不是会挂掉
for example
BufferedReader br = new BufferedReader(new FileReader("xxx"));
int count = 0, read = 0;
while ((read=br.read()) != -1) {
count++;
}
br.close();
System.out.printf("char count = %d\n", count);
难道没有更好的方法了么 我的超大文本考虑到几百M的 那么char数量是亿万级别的 光写一个for循环都要很久吧 那么这样打开这个文件虽说分段读取依然会卡很久 求各位再帮忙想一下吧
1个汉字(gbk):2 byte
1个汉字(utf-8):3 byte读一行,取得String的长度,进行累加。如果是要含回车符则加1,不含则不加。
制取字母的话,char转换为byte的长度为1就是,否则不是。这看你的具体要求是什么?char只是只字母还是可以包含汉字。
我试了一下 用文件长度/2得到的char数是不正确的
这个一方面你给的编码太少 另一方面还要统计汉字有多少和字母有多少岂不是更更慢了
一方面你给的编码太少了 另一方面不仅要统计字母数量还要统计汉字数量 明显比楼上的方法慢多了
大哥,问题是你的题目本身具有两种意义。
简单取得java的char(字母:1byte,汉字:2、3byte)类型有多少个,str.length()就可以了。
skip(Long.MAX_VALUE) 这样就可以返回文件的char数了 各位看看这样做合理不 实际上我也无从验证 但是通过使用来看感觉没什么不正常的地方
这个是skip的方法源码:
while (read < amount) {
if (fillBuf() == -1) {
return read;
}
if (end - pos >= amount - read) {
pos += amount - read;
return amount;
}
// Couldn't get all the characters, skip what we read
read += (end - pos);
pos = end;
}
这个是read的方法源码:
synchronized (lock) {
checkNotClosed();
/* Are there buffered characters available? */
if (pos < end || fillBuf() != -1) {
return buf[pos++];
}
return -1;
}
看上去都是调用了fillBuf的方法 感觉都差不多 所以我还是用skip方法好了 因为看起来更符合鄙人的行为习惯 代码量看上去也比较少 还能减少程序体积 何乐不为呢