读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数
读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数,面试笔试经常遇到的问题
public class CountStringTest { public static void main(String[] args) { try { //统计E盘下面test.txt中的q字符出现的次数 System.out.println("E盘下面test.txt中的q字符出现的次数为:"); System.err.println(count("E:\\test.txt", "q")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static int count(String filename, String target)throws FileNotFoundException, IOException { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); StringBuilder strb = new StringBuilder(); while (true) { String line = br.readLine(); if (line == null) { break; } strb.append(line); } String result = strb.toString(); int count = 0; int index = 0; while (true) { index = result.indexOf(target, index + 1); if (index > 0) { count++; }else { break; } } br.close(); return count; } }
yian