Basic String Manipulation in Kotlin

Lesson Overview

Welcome! In this lesson, we'll delve into the basic string manipulation features of Kotlin, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations. Kotlin offers concise and expressive syntax for these operations, making your code more readable and efficient.

Tokenizing a String in Kotlin

In Kotlin, we can use the split method from the String class or utilize regular expressions to tokenize a string, effectively splitting it into smaller parts or 'tokens'.

Using split method:

Kotlin
fun main() {
    val sentence = "Kotlin is an amazing language!"
    val tokens = sentence.split(" ")
    
    for (token in tokens) {
        println(token)
    }
}

In the example above, we use a space as a delimiter to split the sentence into words. This operation will print each word in the sentence on a new line.

Exploring String Concatenation

In Kotlin, string concatenation can be achieved using the + operator, string templates, or collection operations like joinToString, each providing a unique way to combine strings into a larger string:

Using the + Operator:

Kotlin
fun main() {
    val str1 = "Hello,"
    val str2 = " World!"
    val greeting = str1 + str2
    println(greeting)  // Output: "Hello, World!"
}

Using String Templates:

Kotlin
fun main() {
    val str1 = "Hello,"
    val str2 = " World!"
    val greeting = "$str1$str2"
    println(greeting)  // Output: "Hello, World!"
}

Using Collection Operations:

Kotlin provides powerful collection operations like joinToString. Here’s how:

Kotlin
fun main() {
    val strings = listOf("Hello", "World!", "Kotlin", "Collections!")
    val result = strings.joinToString(separator = " ")
    println(result)  // Output: "Hello World! Kotlin Collections!"
}

In this example, we use joinToString to concatenate all elements of the list into a single string with a space separator.

Trimming Whitespaces from Strings

In Kotlin, the trim method can remove both leading and trailing whitespaces from a string:

Kotlin
fun main() {
    var str = "    Hello, World!    " // string with leading and trailing spaces
    str = str.trim() // remove leading and trailing spaces
    println(str) // Output: "Hello, World!"
}

In this example, trim is used to remove leading and trailing whitespaces from a string.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal