昨天参加了深圳迅雷的二面:
又有一上机题:
读一文本文件:Search.txt
给定一个字符串
算出给定字符串在Txt文件中出现的次数、每行的偏移量、行号和该行内容:
【60分钟题,只用记事本和JDK工具】
package com.xunlei; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.Scanner; public class SearchTxt { public static void main(String[] args) { // 读取要比对的子串 System.out.print("请输入要查找的字符串:"); Scanner scanner = new Scanner(System.in); String subStr = scanner.next(); BufferedReader br = null; try { File file = new File("D:/search.txt"); if (!file.exists()) { file.createNewFile(); } br = new BufferedReader(new InputStreamReader(new FileInputStream( file))); // 定义num int num = 0; // 定义行 int row = 0; // 定义原字符串 String superStr = null; while ((superStr = br.readLine()) != null) { row++; num += findNum(superStr, subStr, row); } System.out.println("子串" + subStr + "在Txt文本中出现的次数:" + num); } catch (Exception e) { } finally { } } public static int findNum(String superStr, String subStr, int row) { char[] ch1 = superStr.toCharArray(); char[] ch2 = subStr.toCharArray(); // 记录次数 int num = 0; for (int i = 0, j = 0; i < ch1.length; i++) { if (ch2[j] == ch1[i]) { j++; if (j == ch2.length) { num++; // 第几行有相同的子串 System.out.println("第" + row + "行:" + superStr); // 偏移量为 System.out.println("偏移量为:" + (i - j + 2)); // i重置为 (i-j+1) i = i - j + 1; // j重置为0 j = 0; } } else { j = 0; } } return num; } }