服务类
package serves;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class serves {
String xml;
String word;
Scanner scanner =new Scanner(System.in);
public void readTXT(){
try{
StringBuffer buffer = new StringBuffer();
BufferedReader bf= new BufferedReader(new FileReader("D:\\数据结构\\数据结构3.txt"));
String s = null;
while((s = bf.readLine())!=null){
buffer.append(s.trim());
}
xml = buffer.toString();
System.out.println(xml);
}catch (IOException e){
System.out.println(e.getMessage());
}
}
public void start(){
int count;
readTXT();
System.out.println("请输入要查询的单词");
word=scanner.next();
count=bF(xml,word);
if(count==0){
System.out.println("未找到单词");
}
else{
System.out.println("一共找到"+count+"个");
}
}
public int bF(String a,String b){
int num=0;
int i=0;
int j=0;
int t;
char []a1=a.toCharArray();
char []b1=b.toCharArray();
while(i<=a1.length){
t=i;
for(j=0;j<b1.length&&i<a1.length;j++)
{
if(a1[i]!=b1[j])
{
break;
}
else{
i++;
}
}
if((i-t)>=b1.length){
location(t,b);
num++;
i=t+b1.length-1;
}
else {
i=t+1;
}
}
return num;
}
public void location(int x,String word){
int t=x+word.length()-1;
System.out.println("单词位置:"+x+"~"+t);
}
}
测试类
package test;
import serves.serves;
public class test {
public static void main(String[]args){
serves action=new serves();
action.start();
}
}
运行结果