簡體   English   中英

如何在文件中解析與生成的字符串匹配的字符串?

[英]How can I parse through a file for a string matching a generated string?

我的頭銜很差,我通常不擅長制造那些。

我有一個程序,該程序將生成輸入單詞的所有排列,並且應該檢查這些單詞是否是單詞(檢查字典),並輸出是的單詞。 真的,我只需要最后一部分,就無法弄清楚如何解析文件。

我取出那里的內容(現在顯示“ String words =”),因為它確實使事情變得更糟(是一個if語句)。 現在,它將要做的就是輸出所有排列。

編輯:我應該添加在嘗試將文件轉到列表中(而不是當前使用的字符串格式)時添加的try / catch。 所以現在它什么也沒做。 還有一件事:是否有可能(以及如何真正地)使排列顯示的字符比輸入的字符少? 不好意思的措詞,例如如果我輸入五個字符,則顯示所有五個字符排列,以及四個,三個,兩個和一個。

import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;

public class Permutations
{
  public static void main(String[] args) throws Exception
  {
    out.println("Enter anything to get permutations: ");
    Scanner scan = new Scanner(System.in);
    String io = scan.nextLine();
    String str = io;
    StringBuffer strBuf = new StringBuffer(str);
    mutate(strBuf,str.length());
  }

  private static void mutate(StringBuffer str, int index)
  {
    try
    {
      String words = FileUtils.readFileToString(new File("wordsEn.txt"));

      if(index <= 0)
      {
        out.println(str);
      }

      else
      {
        mutate(str, index - 1);
        int currLoc = str.length()-index;
        for (int i = currLoc + 1; i < str.length(); i++)
        {
          change(str, currLoc, i);
          mutate(str, index - 1);
          change(str, i, currLoc);
        }
      }
    }
    catch(IOException e)
    {
      out.println("Your search found no results");
    }
  }
  private  static void change(StringBuffer str, int loc1, int loc2)
  {
    char t1 = str.charAt(loc1);
    str.setCharAt(loc1, str.charAt(loc2));
    str.setCharAt(loc2, t1);
  }
} 

如果文件中的每個單詞實際上都在不同的行上,則可以嘗試以下操作:

BufferedReader br = new BufferedReader(new FileReader(file));  
String line = null;  
while ((line = br.readLine()) != null)  
{  
    ... // check and print here
} 

或者,如果您想嘗試其他方法,則Apache Commons IO庫提供了一個名為LineIterator東西。

讀取器中各行的迭代器。 LineIterator擁有對打開的Reader的引用。 完成迭代器后,應關閉閱讀器以釋放內部資源。 這可以通過直接關閉閱讀器,或通過在迭代器上調用close()或closeQuietly(LineIterator)方法來完成。

推薦的使用模式是:

LineIterator it = FileUtils.lineIterator(file, "UTF-8");
    try {
        while (it.hasNext()) {
            String line = it.nextLine();
            // do something with line
        }
    } finally {
        it.close();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM