Java學習(4):統計一個文件中的英文,中文,數字,其他字符以及字符總數
阿新 • • 發佈:2017-07-03
port let args str reader 文件路徑 要求 cnblogs pub
要求:統計一個文件中的英文,中文,數字,其他字符以及字符總數(此隨筆以txt文件為例)
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; /** * 將一個文件中英文,中文,數字,其他字符以及字符總數統計出來 * * @author xcx * @time 2017年6月24日下午4:12:53 */ public class Statistics { public static void main(String[] args) throws IOException { String E1 = "[\u4e00-\u9fa5]";// 中文 String E2 = "[a-zA-Z]";// 英文 String E3 = "[0-9]";// 數字 String file = "d:\\java\\dd.txt";// 要讀的文件路徑 // 創建讀入字節流 FileInputStream fis = new FileInputStream(file); // 將字節流轉化為字符流 InputStreamReader isr = new InputStreamReader(fis); // 轉化為緩存模式 BufferedReader br = new BufferedReader(isr); int numSum = 0;// 記錄數字字符 int letSum = 0;// 記錄英文字符 int punSum = 0;// 記錄標點字符 int chineseSum = 0;// 記錄中文字符 int totle = 0;// 記錄總字符 // 將讀出來的字符復制到ss String ss = ""; String s; while ((s = br.readLine()) != null) { ss += s; } // 遍歷字符串 String temp; for (int i = 0; i < ss.length(); i++) { temp = String.valueOf(ss.charAt(i)); if (temp.matches(E1)) {// 如果該字符匹配中文 chineseSum++; } else if (temp.matches(E2)) {// 如果該字符匹配英文 letSum++; } else if (temp.matches(E3)) {// 如果該字符匹配數字 numSum++; } else punSum++;// 其他 } // 總的字符數 totle = numSum + letSum + punSum + chineseSum; // 輸出 System.out.println("數字有:" + numSum + "個"); System.out.println("英文有:" + letSum + "個"); System.out.println("其他字符有:" + punSum + "個"); System.out.println("中文有:" + chineseSum + "個"); System.out.println("總的字符有:" + totle + "個"); } }
Java學習(4):統計一個文件中的英文,中文,數字,其他字符以及字符總數