統計一個txt文本文件中字母和數字的數量
思路:1、按行讀取這個文件
2、遍歷每一行數據
3、將一行的數據的每一個數據轉換爲char類型
4、根據char字符判斷是數字或者字母,若是將數量加一
5、關閉流
示例如下:
public static void main(String[] args) {
try {
File file = new File("C:/tools/aaa.txt");
FileReader fr = new FileReader(file);
BufferedReader bf = new BufferedReader(fr);
String str = bf.readLine();
int num = 0;
int word = 0;
while (str != null) {
for (int i = 0; i < str.length(); i++) {
char s = str.charAt(i);
if (('A' <= s && s <= 'Z') || ('a' <= s && s <= 'z')) {
word++;
}
if ('0' <= s && s <= '9') {
num++;
}
}
str = bf.readLine();
}
bf.close();
fr.close();
System.out.println("字母的數量: "+word+", 數字的數量:"+num);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}