项目三代码实现
文本检索类
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.management.BufferPoolMXBean;
import java.util.Scanner;
/**
* 文本检索类
*/
public class Search {
//待检索文本
String txt;
//目标文本
String word;
Scanner scan = new Scanner(System.in);
/**
* 读取文本文件内容
*/
public void readFile() {
try {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\IDEA\\WordSearch\\text.txt"));
String t = null;
while ((t = bufferedReader.readLine()) != null) {
stringBuffer.append(t.trim());
}
txt = stringBuffer.toString();
System.out.println("文本文件内容:\n" + txt);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* 检索目标文本
*/
public void search() {
int num;
readFile();
System.out.println("请输入要检索的单词:");
word = scan.next();
num=KMP(txt, word);
if(num==0){
System.out.println("未找到单词");
}
else{
System.out.println("一共找到"+num+"个");
}
}
/**
* 获取next数组
* @param T
* @return
*/
public static int[] next(String T) {
char[] t = T.toCharArray();
int[] next = new int[t.length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < t.length - 1) {
if (k == -1 || t[j] == t[k]) {
j++;
k++;
if (t[j] == t[k]) { // 当两个字符相等时要跳过
next[j] = next[k];
} else {
next[j] = k;
}
} else {
k = next[k];
}
}
return next;
}
/**
* KMP算法检索
* @param txt
* @param word
* @return
*/
public int KMP(String txt, String word) {
int num = 0;
int i = 0;
while (i < txt.length()) {
char[] S = txt.toCharArray();
char[] T = word.toCharArray();
int j = 0;
int[] next = next(word);
while (i < S.length && j < T.length) {
if (j == -1 || S[i] == T[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == T.length) {
findIndex(i-j, word);
num++;
}
}
return num;
}
/**
* 获取检索位置
* @param t
* @param word
*/
public void findIndex(int t,String word){
t++;
int s=t+word.length()-1;
System.out.println("文本发现位置:"+t+"~"+s);
}
/**
* 主函数
* @param args
*/
public static void main(String[] args) {
new Search().search();
}
}