1 /** 2 * 寫入一個方法,輸入一個文件名和一個字符串,統計這個字符串在這個文件中出現的次數。 3 * @param fileName 文件名 4 * @param str 查找的字符串 5 * @return 6 * @throws Exception 7 */ 8 //方法一 9 public static int funCount1(String fileName,String str) throws Exception { 10 int count = 0; 11 BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); 12 String line ; 13 StringBuilder sb = new StringBuilder(); 14 while((line = bf.readLine() )!= null) { 15 sb = sb.append(line); 16 } 17 int a = 0; 18 while((a = sb.indexOf(str)) != -1) { 19 sb = sb.delete(a, a + str.length()); 20 count++; 21 } 22 return count; 23 } 24 25 //方法二:正則表達式 26 public static int funCount2(String fileName,String str) throws Exception { 27 int count =0 ; 28 BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); 29 String line ; 30 StringBuilder sb = new StringBuilder(); 31 while((line = bf.readLine() )!= null) { 32 sb = sb.append(line); 33 } 34 String pattern = ".*" + str + ".*"; 35 while(Pattern.matches(pattern, sb.toString())) { 36 count ++; 37 int a = sb.indexOf(str); 38 sb.delete(a, a + str.length()); 39 } 40 return count; 41 }
個人並不推薦正則表達式來寫這道題,因為都要用到indexOf,很明顯用正則還需要編譯正則表達式匹配模式,然后對輸入字符串進行解釋和匹配操作;很明顯復雜了些;
