import java.util.*; import java.io.*; public class SentenceSplitter { public static final String DICTIONARY_FILE = "dictionary.txt"; public static String splitSentence(String sentence, Set dictionary) { if (dictionary.contains(sentence)) { return sentence; } else { for (int i = 1; i < sentence.length(); i++) { // splitting... String left = sentence.substring(0, i); String right = sentence.substring(i); if (dictionary.contains(right)) { // ... recurse String result = splitSentence(left, dictionary); if (result != null) { return result + " " + right; } } // undo sentence = left + right; } } return null; } /* * * Choices? t hisisasentence th isisasentence thi sisasentence ... */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(System.in); String toSplit = ""; while (!toSplit.equals("q")) { System.out.print("Query: "); toSplit = scan.nextLine(); System.out.println("Splitting: " + toSplit); System.out.println("Did you mean: " + splitSentence(toSplit, readDictionary())); } scan.close(); } private static Set readDictionary() throws FileNotFoundException { Scanner input = new Scanner(new File(DICTIONARY_FILE)); Set words = new HashSet(); while (input.hasNext()) { words.add(input.next()); } input.close(); return words; } }