/****************************************************************************** * This program that searches a dictionary file to find palindromes. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.regex.Pattern; import org.pureprogrammer.Utils; public class PalindromeSearch { static boolean isPalindrome(String s) { String s0 = Pattern.compile("\\W+").matcher(s).replaceAll(""); s0 = s0.toLowerCase(); final int S_LEN = Utils.cpLength(s0); if (S_LEN < 4) { return false; } for (int x = 0; x <= (S_LEN - 1) / 2; ++x) { if (Utils.cpAt(s0, x) != Utils.cpAt(s0, S_LEN - 1 - x)) { return false; } } return true; } static void searchTextFile(String filespec) throws IOException { BufferedReader ifh = Files.newBufferedReader(FileSystems.getDefault().getPath(filespec), Charset.forName("UTF-8")); String line; while ((line = ifh.readLine()) != null) { if (isPalindrome(line)) { System.out.println(line); } } try {ifh.close();} catch (IOException ex) {}; } public static void main(String[] args) { if (args.length != 1) { System.out.println(Utils.join("", "Syntax: ", "PalindromeSearch", " {filename}")); System.exit(1); } String filespec = args[0]; try { searchTextFile(filespec); } catch (IOException ex) { System.out.println(Utils.join("", "Error: ", Utils.exceptionMessage(ex))); } } }