Wednesday, April 22, 2015

Check for Palindromes (Java)

Palindromes are words that are the same forward and reverse. For example Boob is a palindrome since bo is the mirror of ob. This code checks to see if two strings are palindromes of each other, etc. This segment of code can be helpful when checking password quality. 



    private boolean isPalindrome () {
       if (compareIgnoreCase(newPassword, reverse(newPassword)))
            return true;
       else
            return false;
    }

    private boolean compareIgnoreCase(char[] string1, char[] string2) {
        if (string1 == null || string1.length == 0) return false;
        if (string2 == null || string2.length == 0) return false;
        if (string1.length != string2.length) return false;

        for (int i = 0; i < string1.length; i++) {
            if (Character.toLowerCase(string1[i]) !=         Character.toLowerCase(string2[i])) return false;
        }

        return true;
    }

    private char[] reverse(char[] password) {
        char[] r = new char[password.length];

        int x = password.length - 1;
        int y = 0;
        while (x >= 0)
            r[y++] = password[x--];

        return r;
    }

No comments:

Post a Comment