寻找最长单词链
用JavaScript substring 方法比较相邻两个字符串的相邻字母,匹配相等则将字符串存入数组,否则继续往下比较。代码如下:
package jielong; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import jielong.MyFile; public class FineWord { public ArrayList<String> words = new ArrayList<>(); public ArrayList<String> wordsList = new ArrayList<>(); public boolean compare(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); return (a.substring(a.length() - 1).equals(b.substring(0, 1))); } public void fileSplit(String path) throws Exception { MyFile file = new MyFile(); String theFileString = file.get(path); if (theFileString == null) { return; } if (theFileString.equals("")) { throw new Exception("空文件"); } for (String word : theFileString.split("\\,|\\,|\\r|\\n|\\.| |\\(|\\)|\\;|\\:|\"|\\?|\\!|\\'| |\\、|\\”|\\“")) { if (!word.equals("")) { words.add(word); } } if (words.size() <= 1) { throw new Exception("文件内单词过少(只有" + words.size() + "个词)"); } } public void wordWrite(int index, String path) throws Exception { MyFile file = new MyFile(); BufferedWriter bf = file.put(path); wordsList.add(words.get(index)); try { for (String string : words) { if (compare(wordsList.get(wordsList.size() - 1), string)) { wordsList.add(string); bf.append(string); bf.newLine(); } } bf.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if (wordsList.size() <= 1) { throw new Exception("没有单词链"); } } public static void main(String[] args) { FineWord aFineWord = new FineWord(); try { aFineWord.fileSplit("D:\\java/eclipse/word/123.txt"); aFineWord.wordWrite(0, "D:\\java/eclipse/word/output.txt"); System.out.println(aFineWord.wordsList); } catch (IOException e) { System.out.println("无此文件"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
package jielong; import java.io.*; import java.nio.file.Paths; import java.util.Scanner; public class MyFile { public String get(String path) throws IOException { Scanner in = null; String File = ""; in = new Scanner(Paths.get(path)); while (in.hasNextLine()) { File += in.nextLine(); } return File; } public BufferedWriter put(String path) { try { FileWriter f = null; BufferedWriter bf = null; try { f = new FileWriter(path); bf = new BufferedWriter(f); } catch (IOException e) { e.printStackTrace(); } return bf; } catch (Exception e) { e.printStackTrace(); } return null; } }