๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin String Methods

A string method is a built-in action that a string can perform. A method call reads the string or builds a changed copy from it.

Capital and small copies

The calls uppercase() and lowercase() each build a changed copy. The last print shows the stored word kept its first spelling.

fun main() {
    val word = "Kotlin"
    println(word.uppercase())
    println(word.lowercase())
    println(word)
}

Finding a piece of text

The call contains() gives true when the piece sits inside the string. It gives false when the piece is not there.

fun main() {
    println("pineapple".contains("apple"))
    println("pineapple".contains("grape"))
}

Swapping a piece of text

The call replace() swaps the first given piece for the second one. The printed line shows coffee where tea stood.

fun main() {
    val text = "I like tea"
    println(text.replace("tea", "coffee"))
}

Checking the edges

The call startsWith() checks the opening letters of a string. The call endsWith() checks the closing letters.

fun main() {
    println("notebook".startsWith("note"))
    println("notebook".endsWith("pen"))
}

Trimming spaces from the ends

The call trim() cuts the spaces at both ends of a string. The length of the trimmed text is 5, which proves the spaces are gone.

fun main() {
    val padded = "  hello  "
    println(padded.trim())
    println(padded.trim().length)
}

Example

fun main() {
    val title = "  Kotlin Guide  "
    val clean = title.trim()
    println(clean)
    println(clean.uppercase())
    println(clean.contains("Guide"))
    println(clean.replace("Guide", "Notes"))
}

Key points

  • Use uppercase() to build a copy with every letter capital.
  • Use lowercase() to build a copy with every letter small.
  • Use contains() to check whether a string holds a given piece of text.
  • Use replace() to swap one piece of text in a string for another piece.
  • Use startsWith() and endsWith() to check the two edges of a string.
  • Use trim() to remove spaces from both ends of a string.

In this example, title holds a string with spaces at both ends and trim() stores the cleaned text in clean. The uppercase print shows KOTLIN GUIDE. The contains print shows true because Guide sits inside the text. The last print swaps Guide for Notes and shows Kotlin Notes.

Note

A method call leaves the stored string unchanged and builds its result as a new value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does println("hello".uppercase()) print?