面試題: 寫入一個方法,輸入一個文件名和一個字符串,統計這個字符串在這個文件中出現的次數。

package testdemo;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class testSelectCount {
	
	/**
	 * 寫入一個方法,輸入一個文件名和一個字符串,統計這個字符串在這個文件中出現的次數。
	 * @param fileName 文件名
	 * @param str 查找的字符串
	 * @return
	 * @throws Exception
	 */
	public int selectCountInfile(String filename,String str) throws IOException {
		
		BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
		
		StringBuilder readLine=new StringBuilder();
		String line;
		/**
		 * BufferedReader的readLine()方法用來讀一行文字, 一行被視爲由換行符('\ n'),回車符('\ r')中的任何一個或隨後的換行符終止
		 */
		while((line=br.readLine())!=null) {
			readLine.append(line);//把讀到的一行文字追加到StringBuilder字符串中
		}
		int index;int count = 0;
		/**
		 * StringBuilder的indexOf(string類型)方法:返回指定子字符串第一次出現的字符串內的索引
		 * 如果字符串參數作爲該對象中的子字符串發生,則返回第一個這樣的子字符串的第一個字符的索引; 如果它不作爲子串發生,則返回-1
		 */
		while ((index=readLine.indexOf(str))!=-1) {
			/**
			 * 刪除此序列的子字符串中的字符
			 */
			readLine.delete(index, index+str.length());
			count++;
		}
		return count;
		
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章