CKTIS / Java
String.compareToIgnoreCase(String) — compare strings ignoring case
Compare two strings lexicographically without distinguishing uppercase from lowercase, and read their order from the sign of the returned `int`.
Version: Java SE 21
Syntax
public int compareToIgnoreCase(String str)
int result = left.compareToIgnoreCase(right);String.compareToIgnoreCase(String) is an instance method of String. The call left.compareToIgnoreCase(right) compares two strings lexicographically, ignoring case. It returns an int: < 0 means left comes before right, == 0 means they compare as equal, and > 0 means left comes after right. Test the sign rather than assuming the result is always -1, 0, or 1.
In Java SE 21, the result has the same sign as compareTo after applying Character.toLowerCase(Character.toUpperCase(cp)) to each Unicode code point cp in both strings. The original strings are unchanged. The method does not use locale rules. To sort text according to the rules of a particular language, use java.text.Collator with the appropriate Locale.
Use compareTo when case should affect lexicographic order, and equalsIgnoreCase when you only need a boolean answer about equality ignoring case. If either left or right is null, left.compareToIgnoreCase(right) throws NullPointerException. With a non-null left, left.equalsIgnoreCase(null) returns false.
Examples
public class Main {
public static void main(String[] args) {
String first = "apple";
String second = "Banana";
System.out.println(first.compareToIgnoreCase("APPLE"));
System.out.println(Integer.signum(first.compareToIgnoreCase(second)));
System.out.println(Integer.signum(second.compareToIgnoreCase(first)));
}
}Result
0 -1 1
`apple` and `APPLE` compare as equal, giving `0`. `apple` comes before `Banana`, and reversing the comparison changes the sign. The last two lines use `Integer.signum` to turn the results into `-1` and `1`.
Related lessons
- Java · Lesson 63 · Basic · Version: 2