java統計檔案中字元,數字,漢字,空格數目
阿新 • • 發佈:2019-02-12
別人發的一個題目:
java上機實現統計D://document/file.txt檔案中出現的字母個數、數字個數、漢字個數、空格個數及行數?
自己實現了下:
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * java實現統計D:/aa.txt檔案中出現的字母個數、數字個數、漢字個數、空格個數及行數 * */ public class StatisticalCharacters { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { String name = "D:/aa.txt"; //檔名 int num = 0; //數字數 int letter = 0; //字母數 int line = 0; //行數 int space = 0; //空格數 int word= 0; //漢字數 try{ File file=new File(name); BufferedReader br= new BufferedReader(new FileReader(file)); String str = null; while((str=br.readLine())!=null){ System.out.println(str); line++; num += countNumber(str); letter += countLetter(str); word += countChinese(str); space += countSpace(str); } }catch(Exception e){ e.printStackTrace(); } System.out.println("數字數:"+num); System.out.println("字母數"+letter); System.out.println("漢字數"+word); System.out.println("空格數"+space); System.out.println("行數"+line); } /** * 統計數字數 * @param str * @return */ public static int countNumber(String str) { int count = 0; Pattern p = Pattern.compile("\\d"); Matcher m = p.matcher(str); while(m.find()){ count++; } return count; } /** * 統計字母數 * @param str * @return */ public static int countLetter(String str) { int count = 0; Pattern p = Pattern.compile("[a-zA-Z]"); Matcher m = p.matcher(str); while(m.find()){ count++; } return count; } /** * 統計漢字數 * @param str * @return */ public static int countChinese(String str) { int count = 0; Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]"); Matcher m = p.matcher(str); while(m.find()){ count++; } return count; } /** * 統計空格數 * @param str * @return */ public static int countSpace(String str) { int count = 0; Pattern p = Pattern.compile("\\s"); Matcher m = p.matcher(str); while(m.find()){ count++; } return count; } }