我正在尝试编写一个文件搜索算法。在这种情况下,例如我的程序识别字符串是否在另一个单词中。例如,如果我想搜索“man”,我会得到其他实例,如“catman”或“manipulate”,这是我不想要的。
package threadedsearch;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Scanner;
public class ThreadedSearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //antikeimeno scanner
// parakatw pairnoume to input apo to xrhsth
System.out.print("Target:");
String Target = scanner.next();
System.out.print("Key:");
String key= scanner.next();
//prospatheia anoigmatos tou arxeiou
int appearances = 0;
int index=0;
//File file= new File(Target); //antikeimeno gia to arxeio
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(Target),"UTF-8"));
LineNumberReader lr=new LineNumberReader(br);
String line;
while ((line = lr.readLine()) != null)
{
index++;
if (line.matches(key)) {
System.out.println("Found at line" + index );
}
else{
System.out.println("To arxeio de vrethike"); //not found
}
}
} catch (FileNotFoundException e) {
System.out.println("To arxeio de vrethike");
e.printStackTrace();
} catch (IOException e) {
}
}
最佳答案
从中汲取灵感:
public static int searchCount(File fileA, String fileWord) throws FileNotFoundException
{
int count = 0;
fileWord = fileWord.trim();
Scanner scanner = new Scanner(fileA);
while (scanner.hasNext()) // Fix issue #2
{
String nextWord = scanner.next().trim();
if (nextWord.equals(fileWord)) { // Fix issue #1
++count;
}
}
//End While
return count;
}
很容易修改它以获得您要查找的内容。
关于java - 查找其他单词中经常包含的小单词的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013849/