.compareTo()
Published Oct 28, 2023
Contribute to Docs
The .compareTo()
method in Kotlin is used to compare two strings lexicographically, meaning it compares the strings character by character based on their Unicode values. It helps determine the relative order of two strings in a dictionary or alphabetically. This method is commonly employed for sorting strings or performing string comparisons.
Syntax
stringOne.compareTo(stringTwo)
stringOne
: The first string to be compared.stringTwo
: The second string to be compared.
If stringOne
comes before stringTwo
lexicographically, .compareTo()
returns a negative value. If they are equal, it returns 0
. If stringOne
comes after stringTwo
lexicographically, .compareTo()
returns a positive value.
Example
This example shows how to use the .compareTo()
method to two strings:
fun main() {val stringOne = "apple"val stringTwo = "banana"val result = stringOne.compareTo(stringTwo)if (result < 0) {println("$stringOne comes before $stringTwo")} else if (result == 0) {println("$stringOne and $stringTwo are the same")} else {println("$stringOne comes after $stringTwo")}}
The code will return the following output:
apple comes before banana
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Kotlin
Learn Kotlin, the expressive, open-source programming language developed by JetBrains.Beginner Friendly9 hours