English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String compareTo() method compares two strings (in alphabetical order) while ignoring case.
Syntax of the compareToIgnoreCase() method of the String class:
string.compareToIgnoreCase(String str)
The compareToIgnoreCase() method of the String class takes a single parameter.
str - String to be compared
If the strings are equal, thenReturns 0, ignoring case
If the string is located before the parameter str in alphabetical order, thenReturns a negative integer
If the string is located before the parameter str in alphabetical order, thenReturns a positive integer
class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "learn java"; String str3 = "Learn Kolin"; int result; //Compare str1and str2 result = str1.compareToIgnoreCase(str2); System.out.println(result); // 0 //Compare str1and str3 result = str1.compareToIgnoreCase(str3); System.out.println(result); // -1 //Compare str3and str1 result = str3.compareToIgnoreCase(str1); System.out.println(result); // 1 } }
Here,}}
If case is ignored, str1and str2is equal. Therefore, str1.compareToIgnoreCase(str2) returns 0.
in alphabetical order, str1in str3before. Therefore, str1.compareToIgnoreCase(str3) returns a negative value, while str3.compareToIgnoreCase(str1) returns a positive value
class Main { public static void main(String[] args) { String str1 = "LEARN JAVA"; String str2 = "Learn Java"; //If str1and str2Equal (ignoring case differences), //Result is 0 if (str1.compareToIgnoreCase(str2) == 0) { System.out.println("str1and str2Equal "); } else { System.out.println("str1and str2Not Equal "); } } }
Output Result
str1and str2Not Equal
If string comparison needs to consider case differences, you can use