Kingsley Ubah 21. Web Developer. Technical Writer. African in Tech.

How to use compareTo() and other string actions in Kotlin

6 min read 1821

How To Use compareTo() And Other String Actions In Kotlin

Kotlin is a statically typed programming language, which means every variable should have one fixed type. There are various built-in Kotlin types, one of which is the String type.

We use the String type to store string values, which are sequences of characters surrounded by double quotes. We can then work with these stored string values in various ways.

Let’s learn more about Kotlin strings and how to work with them. In this guide:

What are strings in Kotlin?

Let’s take a look at an example to understand Kotlin strings better:

val firstName: String = "Kingsley"    

Here, the name of the variable is firstName, the type is String, and the value inside the double quotes "" is Kingsley.

Since we’re assigning the value of the variable equal to Kingsley right away, we can do away with the type definition. As a result, the variable below is equally valid:

val firstName = "Kingsley"    

This convenient Kotlin feature is called type inference. Basically, it means that the compiler can automatically deduce the type of a variable, so we don’t need to specifically indicate it.

Working with strings in Kotlin

A new String object is initialized whenever we use "" to create a string. This object provides us with several built-in properties and methods to help us work with the string value.

Properties give us information about a given string value, such as its length, the position of specific characters in the string, and so on.

Methods are functions that we can call on an object to directly manipulate its value. For example, we could call a method on a string to return a subset of the original string.

Let’s go over how to perform some commonly used string actions in Kotlin.

Retrieving individual characters of a Kotlin string by index

Each character in a string is represented by an index, which is just an integer value. As in most programming languages, we start counting the index from 0. The first character in the string will have an index of 0, the second will have an index of 1, and so on.

We can retrieve a character in the string using its unique index, like so:

fun main() {
    val greeting = "Hi Kingsley"       

    println(greeting[0]) // H
    println(greeting[1]) // i
    println(greeting[2]) // whitespace
    println(greeting[3]) // K
}

Checking if a string is empty in Kotlin

We can check if a variable has an empty string value using the method isEmpty().



Here’s an example of checking for an empty string:

fun main() {
    val emptyStr = ""       

    println(emptyStr.isEmpty()) // true
}

isEmpty() returns a boolean value of true if the string is empty and false if the string contains any characters.

Getting the length of a string in Kotlin

Imagine you have a program in which you want to abbreviate all names that exceed a given length. To do so, you must first get the length of each string.

The length property returns the number of characters present inside the string:

fun main() {
    val greeting = "Hi Kingsley"       

    println(greeting.length) // 11
}

All characters inside the string are counted, including whitespaces.

Getting a string subset in Kotlin

To cut out a portion of a larger string, use Kotlin’s substring() method.

substring() extracts the portion of a string that is between a provided start and end index. In the example below, we are extracting all characters between the 6th index and 11th index:

fun main() {
    val greeting = "Hello Worldd"       

    println(greeting.substring(6, 11)) // World
}

Note that the character at the 6th index is not included, but the character at the 11th index is included.

Joining strings in Kotlin

String concatenation is when two or more strings are merged. A simple way to merge two or more strings is with the addition + operator:

fun main() {
    val firstName = "Kingsley"   
    val lastName = "Ubah"   
    val fullName = firstName + lastName

    println(fullName) // KingsleyUbah
}

You can separate both strings by whitespace or any other character:

fun main() {
    val firstName = "Kingsley"   
    val lastName = "Ubah"   
    val fullName = firstName + " " + lastName

    println(fullName) // Kingsley Ubah
}

You can also use + to embed variables inside a larger string:

fun main() {
    val customer = "Kingsley"
    val totalAmount = 50
    val items = 6

    val msg = "Hi " + customer + ", your cart has a total of " + items + " items and they amount to " + totalAmount + " dollars"

    println(msg)
}

Note that repeated concatenation using + can quickly make your code more difficult to read. You can use a template string to avoid this problem.

A template string allows you to directly embed variables in the main string. With template strings, it’s very easy to spot any missing space.


More great articles from LogRocket:


To include variables in a template string, precede each variable name with a dollar sign $, as shown in the example below:

fun main() {
    val customer = "Kingsley"
    val totalAmount = 50
    val items = 6

    val msg = "Hi $customer, your cart has a total of $items items and they amount to $totalAmount dollars"

    println(msg) 
}

Template strings are one of the many ways to make your code cleaner and more readable in Kotlin.

Using comparison operators to compare Kotlin strings

You can use comparison operators in Kotlin to check if two or more string objects are structurally or referentially equal.

Structural comparison checks if two or more objects have the same value. To check for this kind of equality, we use the double equal sign ==. Here’s an basic example:

fun main() {
    val a = "Hello"
    val b = "Hallo"
    val c = "Hello"

    println(a == b)   // returns false
    println(a == c)   // returns true

}

Because a and c both have the same value, comparing them with == returns true.

Keep in mind that the comparison is case-sensitive. This means that uppercase and lowercase letters are interpreted as being different, so the string “hello” is not the same as “Hello”.

Referential comparison checks if two or more variables point to the same object. For referential comparison, we use the triple equal sign ===, as seen in the example below:

fun main() {
    val str_1 = "Hello"    
    val str_2 = "Hello"
    val str_3 = "Hello World"

    println(str_1 === str_2) // true     
    println(str_1 === str_3) // false
}

The reference comparison between str_1 and str_2 returns true because when the second assignment is made, the Java Virtual Machine (JVM) discovers that the string “Hello” already exists within the pool.

Making the second variable point to the same string object, “Hello,” saves some memory.

However, JVM allocates separate memory for the third variable assignment because the value is different. Hence, the comparison between str_1 and str_3 returns false.

Using the equals() function to compare Kotlin strings

The equals() function should be familiar to those coming from a Java background. Similar to ==, which we saw earlier, equals() checks if two objects have the same content.

Let’s look at an example using this straightforward method to compare strings. Below, we defined four string variables. Out of the four, only a and c are the same.

fun main() {
    val a = "Hello"
    val b = "Hallo"
    val c = "Hello"
    val d = "hello"

    println(a.equals(b))    // returns false
    println(a.equals(c))     // returns true
    println(a.equals(d, true))     // returns true
}

Note that equals() checks are case-sensitive by default, so the string “hello” is not the same as “Hello”.

However, unlike with ==, we can choose to remove case sensitivity by passing a second argument of true in equals(). We did this in the last line, where we compared “Hello” to “hello” and the check returned true.

Using the compareTo() function to compare Kotlin strings

You can also compare strings in Kotlin with compareTo(). Here is the basic syntax for this method:

mainStr.compareTo(otherStr)

While the previous methods return a boolean value (true or false), compareTo() returns an integer:

  • Returns 0 if the main string and the other string are equal
  • Returns a negative number if the other string’s ASCII value is bigger than the main string
  • Returns a positive number if the other string’s ASCII value is smaller than the main string
// Example 1
fun main() {
val a = "Hallo"
val b = "Hello"

println(a.compareTo(b))    // returns -4

}

// Example 2
fun main() {
val a = "Hello"
val b = "Hallo"

println(a.compareTo(b))    // returns 4

}

// Example 3
fun main() {
val a = "Hello"
val b = "Hello"

println(a.compareTo(b))    // returns 0

}

compareTo() string comparisons are case-sensitive by default. Like with equals(), you can override this behavior by passing the argument true.

In the following example, the first check returns a negative value because we explicitly enabled case sensitivity. The second check returns 0 because we disabled case sensitivity.

fun main() {
    val upper: String = "Hello"
    val lower: String = "hello"


    println(upper.compareTo(lower, false))    // returns false (-32)
    println(upper.compareTo(lower, true))     // returns true (0)

}

Replacing strings in Kotlin

The String.replace() method is used to replace strings in Kotlin. The basic syntax is as follows:

mainString.replace(oldValue, newValue)

This method checks for occurrences of the provided old value inside the main string and replaces every instance with the new value. Here’s an example:

fun main() {
    var mainStr = "Replacing Strings in Python"
    val oldValue = "Python"
    val newValue = "Kotlin"

    val newStr = mainStr.replace(oldValue, newValue)

    println(newStr) // Replacing Strings in Kotlin
}

To disable case sensitivity, pass true as the third argument. Let’s see this in action:

var mainStr = "Replacing Strings in python"    
    val oldValue = "Python"
    val newValue = "Kotlin"

    var newStr = mainStr.replace(oldValue, newValue, true)
    println(newStr) // Replacing Strings in Kotlin

As you can see, the case difference between “python” and “Python” was ignored.

Sorting strings in Kotlin

We can sort a string alphabetically in Kotlin by executing the methods toCharArray(), sorted(), and joinToString() on the string in succession.

Suppose you want to reorder the string “elephant” to be in alphabetical order: “aeehlnpt”. First, convert the string to an array with the toCharArray() method. Then, use sorted() to sort the array. Finally, use joinToString() to turn the array back into a String:

fun main() {
    val str = "elephant"
    val arr = str.toCharArray()
    val sorted = arr.sorted().joinToString("")
    println(sorted) // aeehlnpt
}

You can wrap everything inside a custom function and call that function whenever you want to sort a string:

fun sortByAlpha(str: String) {       
    val arr = str.toCharArray()
    println(arr.sorted().joinToString(""))

}
fun main() {
    sortByAlpha("elephant")
}

Summary

In this tutorial, we learned about Kotlin strings and how to perform some common Kotlin string operations. These include getting a string length, sorting strings, joining strings, comparing strings, and using a string template to make your string readable.

I hope you found this comprehensive guide to Kotlin strings helpful. If you want to learn even more, Kotlin provides extensive documentation on strings that goes beyond the properties and methods we reviewed in this post to cover related concepts, such as Kotlin extensions.

Have a great week.

LogRocket: Instantly recreate issues in your Android apps.

LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your Android apps — .

Kingsley Ubah 21. Web Developer. Technical Writer. African in Tech.

Leave a Reply