0

我想实现一个 Java 程序,它在文本文件中搜索短语示例“red or green, blue car, red and blue”,并返回一个匹配,即使它不是该短语的完全匹配,如果没有即使是半场比赛,程序也不应该返回任何比赛。

如果我正在搜索“红色汽车”并且文本文件中的字符串行包含“红色和蓝色”,我希望程序返回红色,这是我正在搜索的一半匹配。

很感谢任何形式的帮助

这就是我到目前为止所做的,所做的就是找到确切的单词

public class StringSearch 
   {
    public static void main(String[] args) 
      {
        String key = "red yellow";
        String strLine;
        try
          {
    FileInputStream fstream = new FileInputStream("C:\\textfile.txt");
    DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
    while ((strLine = br.readLine()) != null) {    
          if(key.equals(strLine))
         {
          System.out.println(" Match For " + strLine );
        }
        else 
         {
         System.out.println( "No Match For "   + key);

        }
     // Print the content on the console
    }
        //Close the input stream
        in.close();

        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

但我想找到的是,如果我正在搜索“red”并且我正在搜索的文本文件中字符串的第一行包含“red car was stollen”,而第二行只包含“red”。我想返回两个匹配项,第一个匹配 100%,第二个匹配 50%。

4

2 回答 2

0

首先,您需要更好地定义您的问题,并为此考虑如果您告诉其他人(按照字面意思解释事情),您会怎么做。他们一次应该检查多少输入?他们应该检查跨度线吗?究竟什么是“半场比赛”?他们应该采取的步骤顺序是什么?

于 2012-11-04T14:34:43.617 回答
0

此代码可能对您有所帮助

import java.io.*;

public class searchfile {
    public static void main(String args[]) {
        try {
            // Open the file c:\test.txt as a buffered reader
            BufferedReader bf = new BufferedReader(new FileReader("c:\\test.txt"));

            // Start a line count and declare a string to hold our current line.
            int linecount = 0;
                String line;

            // Let the user know what we are searching for
            System.out.println("Searching for " + args[0] + " in file...");

            // Loop through each line, stashing the line into our line variable.
            while (( line = bf.readLine()) != null)
            {
                    // Increment the count and find the index of the word
                    linecount++;
                    int indexfound = line.indexOf(args[0]);

                    // If greater than -1, means we found the word
                    if (indexfound > -1) {
                         System.out.println("Word was found at position " + indexfound + " on line " + linecount);
                    }
            }

            // Close the file after done searching
            bf.close();
        }
        catch (IOException e) {
            System.out.println("IO Error Occurred: " + e.toString());
        }
    }
}

并将其运行为 c:\>java searchfile "bluecar"

于 2012-11-04T14:36:30.343 回答