- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin String - compareTo() Function
The Kotlin string compareTo() function is used to compare two strings lexicographically. It determines the ordering of two strings and returns zero if current object is equal to the specified other object, a negative number if it's less than other, or a positive number if it's greater than other.
Syntax
Following is the syntax of the Kotlin string compareTo() function −
fun compareTo(other: String): Int
Parameters
This function accepts another object as a parameter, which represents a string that needs to be compared with the current string.
Return value
This function returns integer value.
Example 1: Compare String with Other String
Following is the basic example, here how we can use compareTo() to compare current string with other string lexicographically in kotlin −
fun main() {
val string1 = "Kotlin"
val string2 = "Kotlin"
val string3 = "Java"
// Lexicographical comparison
println(string1.compareTo(string2))
println(string1.compareTo(string3))
}
Output
Following is the output −
0 1
Example 2: Impact of Whitespace in String
Now, let's look at another example of the CompareTo() function. What if both the strings are equal but the other one has whitespace?
fun main() {
val string1 = "Kotlin"
val string2 = "Kotlin "
// Lexicographical comparison
println(string1.compareTo(string2))
}
Output
Following is the output −
-1
Example 3: Case-Insensitive Comparison
In this following example we use CompareTo() function to perform a case-insensitive comparison −
fun main() {
val string1 = "Kotlin"
// Case-insensitive comparison
println(string1.compareTo("kotlin", ignoreCase = true))
println(string1.compareTo("kotlin"))
}
Output
Following is the output −
0 -32