import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class search {
String textDocument;
String willSearchWord;
Scanner scanner =new Scanner(System.in);
public void readText(){
try{
StringBuffer buffer = new StringBuffer();
BufferedReader bufferedReader= new BufferedReader(new FileReader("C:\\Users\\贺祥\\Desktop\\1.txt"));
String readLine = null;
while( (readLine = bufferedReader.readLine()) != null ){
buffer.append(readLine.trim());
}
//转换为字符串型
textDocument = buffer.toString();
}catch (IOException e){
System.out.println(e.getMessage());
}
}
public void begin(){
//寻找到的单词的计数器
int count;
//调用读文件
readText();
System.out.println("请输入要查询的单词");
willSearchWord = scanner.next();
//调用KMP方法
count = KMP(textDocument, willSearchWord);
if(count==0){
System.out.println("未找到单词");
}
else{
System.out.println("一共找到"+count+"个");
}
}
/**
* KMP算法
* @param textDocument
* @param willSearchWord
* @return
*/
public int KMP(String textDocument, String willSearchWord) {
int num = 0;
int i = 0;
while( i< textDocument.length())
{
//字符型数组
char[] charTextDocument = textDocument.toCharArray();
char[] charWillSearchWord = willSearchWord.toCharArray();
int j = 0; // 模式串的位置
int[] next = getNext(willSearchWord);
while (i < charTextDocument.length && j < charWillSearchWord.length) {
if (j == -1 || charTextDocument[i] == charWillSearchWord[j]) { // 当j为-1时,要移动的是i,当然j也要归0
i++;
j++;
} else {
j = next[j]; // j回到指定位置
}
}
if (j == charWillSearchWord.length) {
site(i-j,willSearchWord);
num++;
}
}
return num;
}
public static int[] getNext(String willSearchWord) {
char[] charwillSearchWord = willSearchWord.toCharArray();
int[] next = new int[charwillSearchWord.length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < charwillSearchWord.length - 1) {
if (k == -1 || charwillSearchWord[j] == charwillSearchWord[k]) {
if (charwillSearchWord[++j] == charwillSearchWord[++k]) { // 当两个字符相等时要跳过
next[j] = next[k];
} else {
next[j] = k;
}
} else {
k = next[k];
}
}
return next;
}
public void site(int firstLength, String word){
int allLength = firstLength+word.length()-1;
System.out.println("单词位置:"+firstLength+"~"+allLength);
}
}
public class test {
public static void main(String[]args){
search input=new search();
input.begin();
}