Question

I saw this in my readings that allows you to compare two strings using the compareToCaseIgnore(String).

public class CompareWithoutCase
{
   public static void main(String [] args)
   {
        String name1, name2;  // To hold two names

        // Create a Scanner object to read input.
        Scanner keyboard = new Scanner(System.in);

        // Get a name.
        System.out.print("Enter a name: ");
        name1 = keyboard.nextLine();

        // Get another name.
        System.out.print("Enter another name: ");
        name2 = keyboard.nextLine();

        // Compare the names.
        if (name1.compareToIgnoreCase(name2) < 0)
        {
           System.out.println(name1 + " is less than " + name2);
        }
        else if (name1.compareToIgnoreCase(name2) == 0)
        {
           System.out.println(name1 + " is equal to " + name2);
        }
        else if (name1.compareToIgnoreCase(name2) > 0)
        {
           System.out.println(name1 + " is greater than " + name2);
        }
    }
}

My question is why would a string such as cli be different from ilc in value if they hold the same characters? I've read in another question that a lower case letter is different from a capital letter in value and I somewhat understand that, though not fully. Is there any place I can find an explanation for this in depth or can someone explain with a few examples? I input

cli

for the first string and

ilc

for the second name and got

cli is less than ilc

Why is one less than the other with the same letters in each string?

Était-ce utile?

La solution

Lower case and upper case letters do have different ASCII values, but they are separated by a constant (42, I think). That is to say, A is the same distance from a as B is from b as C is from c, etc.

ilc and cli are different in that they're completely different characters.

compareToIgnoreCase (or equalsIgnoreCase) does a character by character comparison. That is, it compares the character at index 0 of str1 to the character at index 0 of str2. And so on, for every index of the two strings being compared.

If you compare ilc and cli, then i in ilc is compared to c in cli (and they're different), so the comparison returns false. The comparison doesn't care if i appears elsewhere in the second string, it only cares if i or I exists in the second string at the same index it exists in the first string (and so on for all the rest of the characters, though I imagine it's probably optimized to return false as soon as it finds one difference).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top