CharSequence equals Ignore Case - Java java.lang

Java examples for java.lang:CharSequence

Description

CharSequence equals Ignore Case

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        CharSequence seq1 = "java2s.com";
        CharSequence seq2 = "java2s.com";
        System.out.println(equalsIgnoreCase(seq1, seq2));
    }//from  ww w . ja v a  2s  .  com

    public static boolean equalsIgnoreCase(CharSequence seq1,
            CharSequence seq2) {
        if ((seq1 == null) && (seq2 == null)) {
            return true;
        }

        if ((seq1 == null) || (seq2 == null)) {
            return false;
        }

        if (seq1.length() != seq2.length()) {
            return false;
        }
        for (int i = 0; i < seq1.length(); i++) {
            char one = seq1.charAt(i);
            char two = seq2.charAt(i);
            if (one != two) {
                if (Character.isLetter(one) && Character.isLetter(two)) {
                    // string equalsIgnoreCase does this (both upper and lower
                    // check)
                    one = Character.toUpperCase(one);
                    two = Character.toUpperCase(two);
                    if (one != two) {
                        one = Character.toLowerCase(one);
                        two = Character.toLowerCase(two);
                        if (one != two) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    public static void toUpperCase(StringBuilder builder) {
        for (int i = 0; i < builder.length(); i++) {
            if (Character.isLowerCase(builder.charAt(i))) {
                builder.setCharAt(i,
                        Character.toUpperCase(builder.charAt(i)));
            }
        }
    }

    public static void toLowerCase(StringBuilder builder) {
        for (int i = 0; i < builder.length(); i++) {
            if (Character.isUpperCase(builder.charAt(i))) {
                builder.setCharAt(i,
                        Character.toLowerCase(builder.charAt(i)));
            }
        }
    }
}

Related Tutorials