I've just spent almost hour debugging a List<String>
in my code which was being sorted wrong by my Comparator
.
Turns out that string.compareTo(string2)
is case-sensitive. Meaning that all Capital letters come before the lowercase letters. e.g. "Z" comes before "d".
Is there any better way of comparing 2 Strings
inside a Comparator
and sorting them alphabetically ascending without them being case sensitive other then string.toLowerCase().compareTo(string2.toLowerCase());
?
Edit: There's a possibility of any accented letter appearing in my String
like for example: ä, ö, ü, é, è, etc.
Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. Example 1: This example uses toUpperCase() function to compare two strings.
CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.
To compare cells case insensitive, you can use this formula =AND(A1=B1), remember to press Shift + Ctrl + Enter keys to get the correct result. 2.
How to compare two strings without case sensitive in Java. The equalsIgnoreCase () method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Case-insensitive means the string which you are comparing should exactly be the same as a string which is to be compared but both strings can be either in upper case or lower case. (ie., different cases) Example 1: Conversion to lower case for comparison
Compare Two Strings in C# (case sensitivity or not) In this examples, we’ll learn how to compare two strings in C# Console Application using case sensitive and case insensitive. Example 1: Compare Two Strings with case sensivity. C# Code: string str1 = "Csharp"; string str2 = "csharp";
You could set the entire string to lower case by using the String prototype method toLowerCase () and compare the two that way. To keep the input the same, mutate the string during your switch statement: You should always compare uppercase string with uppercase values in case sensitive languages. Or lower with lower.
You have two options provided in String itself:
String.compareToIgnoreCase(String)
: case insensitive variant of compareTo
)String.CASE_INSENSITIVE_ORDER
: Comparator
that has the same ordering as compareToIgnoreCase
java.text.Collator
and java.text.RuleBasedCollator
As a tip: your first stop should be the Javadoc, not post a question on Stack Overflow: the Javadoc is extensive and will usually provide a quick answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With