String compareto java
Java String compareTo() Method with examples
By Chaitanya Singh | Filed Under: String handling
The Java String compareTo() method is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.
Java String compareTo() method
We have following two ways to use compareTo() method:
Here the comparison is between string literals. For example string1.compareTo(string2) where string1 and string2 are String literals.
Here the comparison is between a string and an object. For example string1.compareTo(«Just a String object») where string1 is a literal and it’s value is compared with the string specified in the method argument.
Java String compareTo() method Example
Here we have three Strings and we are comparing them with each other using compareTo() method.
How to find length of a string using String compareTo() method
Here we will see an interesting example of how to use the compareTo() method to find the length of a string. If we compare a string with an empty string using the compareTo() method then the method would return the length of the non-empty string.
In the above code snippet, the second compareTo() statement returned the length in negative number, this is because we have compared the empty string with str1 while in first compareTo() statement, we have compared str1 with empty string.
Lets see the complete example:
Output:
Is Java String compareTo() method case sensitive?
In this example, we will compare two strings using compareTo() method. Both the strings are same, however one of the string is in uppercase and the other string is in lowercase.
Output:
As you can see that the output is not zero, which means that compareTo() method is case sensitive. However we do have a case insensitive compare method in string class, which is compareToIgnoreCase(), this method ignores the case while comparing two strings.
Comments
If both the strings has space in them?
Also if the no of characters in both the strings are not equal then what will be the output?
I think a better description of what this method does is that it compares the FIRST character that is not equal in both strings. Anything after that will NOT be compared, whether one string has more or less characters are equal or not. The interger given in the result is based on the difference in value of the characters in the ASCII chart.
This would apply for the space as well. If space is placed as the first distinct character in the two strings, then it would be compared depending the ASCII values of the two characters.
For example, if you compared a space character (which has a ASCII value of 32) to a comma (which has an ASCII value of 44) using the compareTo() method, assuming that they are the first distinct chracters found in the two strings, then the result would be the difference between 32 and 44, which is -12.
Java get String CompareTo as a comparator object
I would like to sort and binary search a static array of strings via the String.CompareTo comparator.
The problem is that both sorting, and binary searching requires that a Comparator object be passed in — So how do I pass in the built in string comparator?
12 Answers 12
The Arrays class has versions of sort() and binarySearch() which don’t require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.
You may write your own comparator
If you do find yourslef needing a Comparator , and you already use Guava , you can use Ordering.natural() .
This is a generic Comparator for any kind of Comparable object, not just String :
How to use with String :
Again, don’t need the comparator for Arrays.binarySearch(Object[] a, Object key) so long as the types of objects are comparable, but with lambda expressions this is now way easier.
Simply replace the comparator with the method reference: String::compareTo
You could also use
but even before lambdas, there were always anonymous classes:
Also, if you want case-insensitive comparison, in recent versions of Java the String class contains a public static final field called CASE_INSENSITIVE_ORDER which is of type Comparator , as I just recently found out. So, you can get your job done using String.CASE_INSENSITIVE_ORDER .
Ok this is a few years later but with java 8 you can use Comparator.naturalOrder():
Returns a comparator that compares Comparable objects in natural order. The returned comparator is serializable and throws NullPointerException when comparing null.
We can use the String.CASE_INSENSITIVE_ORDER comparator to compare the strings in case insensitive order.
To generalize the good answer of Mike Nakis with String.CASE_INSENSITIVE_ORDER , you can also use :
You can use the StringUtils.compare(«a», «b»)
Regarding Nambari’s answer there was a mistake. If you compare values using double equal sign == program will never reach compare method, unless someone will use new keyword to create String object which is not the best practice. This might be a bit better solution:
String. Compare To Метод
Определение
Сравнивает данный экземпляр с заданным объектом или строкой String и возвращает целое число, которое показывает, расположен ли данный экземпляр перед, после или на той же позиции в порядке сортировки, что и заданный объект или строка String. Compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String.
Перегрузки
Сравнивает данный экземпляр с указанным объектом Object и показывает, расположен ли экземпляр перед, после или в той же позиции в порядке сортировки, что и заданный объект Object. Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.
Сравнивает данный экземпляр с заданным объектом String и показывает, расположен ли данный экземпляр перед, после или на той же позиции в порядке сортировки, что и заданная строка. Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.
Комментарии
Обе перегрузки метода CompareTo выполняют сравнение с учетом языка и региональных параметров, а также с учетом регистра. Both overloads of the CompareTo method perform culture-sensitive and case-sensitive comparison. Этот метод нельзя использовать для сравнений без учета языка и региональных параметров или порядкового сравнения. You cannot use this method to perform culture-insensitive or ordinal comparisons. Для ясности кода рекомендуется избегать метода CompareTo и вызывать метод Compare. For code clarity, we recommend that you avoid the CompareTo method and call the Compare method instead.
CompareTo(Object)
Сравнивает данный экземпляр с указанным объектом Object и показывает, расположен ли экземпляр перед, после или в той же позиции в порядке сортировки, что и заданный объект Object. Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.
Параметры
Объект, имеющий значение String. An object that evaluates to a String.
Возвращаемое значение
32-битовое целое число со знаком, которое показывает, расположен ли данный экземпляр перед, после или на той же позиции в порядке сортировки, что и параметр value . A 32-bit signed integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the value parameter.
Значение Value | Условие Condition | ||||||||
---|---|---|---|---|---|---|---|---|---|
Меньше нуля Less than zero | Данный экземпляр предшествует параметру value . This instance precedes value . | ||||||||
Ноль Zero | Данный экземпляр имеет ту же позицию в порядке сортировки, что и value . This instance has the same position in the sort order as value . | ||||||||
Больше нуля Greater than zero | Данный экземпляр стоит после параметра value . This instance follows value . Параметр value равен null . value is null . РеализацииИсключенияvalue не является объектом типа String. value is not a String. ПримерыВ следующем примере метод CompareTo используется с Object. The following example uses the CompareTo method with an Object. Поскольку он пытается сравнить экземпляр String с TestClass ным объектом, метод создает исключение ArgumentException. Because it attempts to compare a String instance to a TestClass object, the method throws an ArgumentException. Комментарииvalue должен быть Stringным объектом. value must be a String object. Метод CompareTo был разработан главным образом для использования в операциях сортировки или алфабетизинг. The CompareTo method was designed primarily for use in sorting or alphabetizing operations. Его не следует использовать, когда основной целью вызова метода является определение того, эквивалентны ли две строки. It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. Чтобы определить, эквивалентны ли две строки, вызовите метод Equals. To determine whether two strings are equivalent, call the Equals method. Этот метод выполняет сравнение по словам (с учетом регистра и с учетом языка и региональных параметров), используя текущий язык и региональные параметры. This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. Дополнительные сведения о сортировке по словам, строкам и порядковым номерам см. в разделе System.Globalization.CompareOptions. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. Дополнительные сведения о поведении этого метода см. в разделе «Примечания» метода String.Compare(String, String). For more information about the behavior of this method, see the Remarks section of the String.Compare(String, String) method. Примечания для тех, кто вызывает этот методНаборы символов содержат символы, которые могут игнорироваться. Character sets include ignorable characters. Метод CompareTo(Object) не учитывает такие символы при выполнении сравнения с учетом языка и региональных параметров. The CompareTo(Object) method does not consider such characters when it performs a culture-sensitive comparison. Например, если следующий код выполняется в .NET Framework 4 .NET Framework 4 или более поздней версии, сравнение «Animal» с «Ani-недействительностью» (с использованием мягкого дефиса или U + 00AD) указывает на то, что две строки эквивалентны. For example, if the following code is run on the .NET Framework 4 .NET Framework 4 or later, a comparison of «animal» with «ani-mal» (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent. Чтобы распознать игнорируемые символы в сравнении строк, вызовите метод CompareOrdinal(String, String). To recognize ignorable characters in a string comparison, call the CompareOrdinal(String, String) method. ДополнительноCompareTo(String)Сравнивает данный экземпляр с заданным объектом String и показывает, расположен ли данный экземпляр перед, после или на той же позиции в порядке сортировки, что и заданная строка. Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string. ПараметрыСтрока, сравниваемая с данным экземпляром. The string to compare with this instance. Возвращаемое значение32-битовое целое число со знаком, которое показывает, расположен ли данный экземпляр перед, после или на той же позиции в порядке сортировки, что и параметр strB . A 32-bit signed integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the strB parameter.
|