0

「赤か緑、青の車、赤と青」という語句の例をテキストファイルから検索し、語句の完全一致でなくても一致を返す Java プログラムを実装したい。半一致でも、プログラムは no match を返す必要があります。

「赤い車」を検索していて、テキスト ファイルの文字列行に「赤と青」が含まれている場合、プログラムは、検索していたものと半分一致する赤を返します。

どんな助けでも大歓迎です

これは私がこれまで行ってきたことです。これが行うことは、正確な単語を見つけることだけです

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());
        }
    }
}

しかし、検索したいのは、「赤」を検索していて、検索しているテキスト ファイルの文字列の最初の行に「赤い車が盗まれました」が含まれ、2 行目には「赤」だけが含まれている場合です。最初の一致は 100% 一致、2 番目は 50% 一致の 2 つの一致を返します。

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 に答える