String Functions in Kotlin

The standard library in Kotlin provides many useful string-related functions. Here are some examples to give you a sense of the available operations.

import kotlin.text.*

// We define a shorthand for println as we'll use it a lot below.
val p = ::println

fun main() {
    // Here's a sample of the functions available for string operations.
    // In Kotlin, these are typically extension functions on the String class,
    // so we call them directly on the string object.

    p("Contains:  ${"test".contains("es")}")
    p("Count:     ${"test".count { it == 't' }}")
    p("StartsWith: ${"test".startsWith("te")}")
    p("EndsWith:  ${"test".endsWith("st")}")
    p("IndexOf:   ${"test".indexOf("e")}")
    p("Join:      ${listOf("a", "b").joinToString("-")}")
    p("Repeat:    ${"a".repeat(5)}")
    p("Replace:   ${"foo".replace("o", "0")}")
    p("Replace:   ${"foo".replaceFirst("o", "0")}")
    p("Split:     ${"a-b-c-d-e".split("-")}")
    p("Lowercase: ${"TEST".lowercase()}")
    p("Uppercase: ${"test".uppercase()}")
}

When you run this program, you’ll see:

$ kotlin string-functions.kt
Contains:  true
Count:     2
StartsWith: true
EndsWith:  true
IndexOf:   1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     [a, b, c, d, e]
Lowercase: test
Uppercase: TEST

In Kotlin, many of these operations are implemented as extension functions on the String class, which allows for a more object-oriented style of calling these functions directly on string objects. The functionality is similar to the Go version, but the syntax is more idiomatic to Kotlin.

For more string operations, you can refer to the Kotlin standard library documentation for the String class.