0
0
Kotlinprogramming~5 mins

String methods (substring, split, trim) in Kotlin

Choose your learning style9 modes available
Introduction

String methods help you change or get parts of text easily. They make working with words and sentences simple.

You want to get a smaller part of a long text.
You need to break a sentence into words or pieces.
You want to remove extra spaces from the start or end of a text.
You want to check or change parts of a user's input.
You want to prepare text for saving or showing neatly.
Syntax
Kotlin
class StringExample {
    fun substringExample(text: String, startIndex: Int, endIndex: Int): String {
        return text.substring(startIndex, endIndex)
    }

    fun splitExample(text: String, delimiter: String): List<String> {
        return text.split(delimiter)
    }

    fun trimExample(text: String): String {
        return text.trim()
    }
}

substring(startIndex, endIndex) gets text from startIndex up to but not including endIndex.

split(delimiter) breaks text into a list where the delimiter appears.

trim() removes spaces at the start and end of the text.

Examples
Gets the first 5 letters from the text.
Kotlin
val text = "Hello Kotlin"
val part = text.substring(0, 5)  // "Hello"
Splits the string into a list of fruits by comma.
Kotlin
val text = "apple,banana,orange"
val fruits = text.split(",")  // ["apple", "banana", "orange"]
Removes spaces before and after the word.
Kotlin
val text = "   hello   "
val cleanText = text.trim()  // "hello"
Trimming an empty string stays empty.
Kotlin
val emptyText = ""
val result = emptyText.trim()  // ""
Sample Program

This program shows how to trim spaces, get a substring, and split a sentence into words.

Kotlin
fun main() {
    val originalText = "  Kotlin is fun!  "
    println("Original: '" + originalText + "'")

    val trimmedText = originalText.trim()
    println("Trimmed: '" + trimmedText + "'")

    val subText = trimmedText.substring(0, 6)
    println("Substring (0 to 6): '" + subText + "'")

    val words = trimmedText.split(" ")
    println("Split by space: " + words)
}
OutputSuccess
Important Notes

Time complexity: substring and trim are O(n) where n is the length of the string; split depends on the number of delimiters.

Space complexity: These methods create new strings or lists, so they use extra memory proportional to the output size.

Common mistake: Using substring with wrong indexes can cause errors or unexpected results.

Use trim to clean user input; use split to separate words; use substring to get parts of text.

Summary

substring extracts part of a string by index.

split breaks a string into pieces using a delimiter.

trim removes spaces from the start and end of a string.