對於給定的文字檔案,計算一個字串在檔案中出現的次數
---------------------------------------------------------------------------位元組流--------------------------------------------------------------------------------
package filetest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class StringTimes { static Scanner scan = new Scanner(System.in); public static int getKeyStringCount(String str,String key){ //獲取字串key在字串str中出現的次數 int count = 0 ; int index = 0; while((index=str.indexOf(key,index))!=-1) {
//從index下標開始key存在於str作為控制迴圈的條件,
//indexOf(key,index) 表示從字串的第index下標開始字串key第一次出現的位置 index = index + key.length(); count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub File file = new File("C:\\a.txt"); FileInputStream fis = null ;//定義位元組流 try { fis = new FileInputStream(file); int len = 0; String str = null; byte[] by = new byte[1024]; //獲取檔案中的字串,並將其存入by中 while((len=fis.read(by))!=-1) { str = new String(by,0,len); } System.out.println("請輸入你要查詢的字串"); String key = scan.nextLine(); int count = getKeyStringCount(str, key); System.out.println(count); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally { try { if( fis!=null ) fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
} --------------------------------------------------------------------------------字元流-----------------------------------------------------------------------------
package filetest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; public class StringTimes { static Scanner scan = new Scanner(System.in); public static int getKeyStringCount(String str,String key){ int count = 0 ; int index = 0; while((index=str.indexOf(key,index))!=-1) { index = index + key.length(); count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub File file = new File("C:\\a.txt"); FileInputStream fis = null ; try { fis = new FileInputStream(file); int len = 0; String str = null; byte[] by = new byte[1024]; while((len=fis.read(by))!=-1) { str = new String(by,0,len); } System.out.println("請輸入你要查詢的值"); String key = scan.nextLine(); int count = getKeyStringCount(str, key); System.out.println(count); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally { try { if( fis!=null ) fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
}