Bird
Raised Fist0
Kotlinprogramming~5 mins

String methods (substring, split, trim) in Kotlin

Choose your learning style10 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.

Practice

(1/5)
1. What does the Kotlin trim() method do when called on a string?
easy
A. Converts the string to uppercase
B. Splits the string into parts based on spaces
C. Extracts a part of the string by index
D. Removes spaces from the start and end of the string

Solution

  1. Step 1: Understand the purpose of trim()

    The trim() method removes whitespace characters from the beginning and end of a string.
  2. Step 2: Compare with other string methods

    Unlike split() or substring(), trim() does not split or extract parts but cleans spaces around the string.
  3. Final Answer:

    Removes spaces from the start and end of the string -> Option D
  4. Quick Check:

    trim() removes outer spaces [OK]
Hint: trim() cleans spaces only at string edges [OK]
Common Mistakes:
  • Thinking trim() splits the string
  • Confusing trim() with substring()
  • Assuming trim() changes case
2. Which of the following is the correct Kotlin syntax to get a substring from index 2 to 5 (exclusive) of a string text?
easy
A. text.substring(2..5)
B. text.subString(2, 5)
C. text.substring(2, 5)
D. text.substring(2, 6)

Solution

  1. Step 1: Recall Kotlin substring syntax

    The correct method call is substring(startIndex, endIndex) where endIndex is exclusive.
  2. Step 2: Check each option

    text.substring(2..5) uses a range which is invalid for substring. text.subString(2, 5) has wrong capitalization. text.substring(2, 6) uses 6 as endIndex which extracts more characters than asked.
  3. Final Answer:

    text.substring(2, 5) -> Option C
  4. Quick Check:

    substring(start, end) uses exclusive end [OK]
Hint: Use substring(start, end) with end exclusive [OK]
Common Mistakes:
  • Using range syntax inside substring
  • Wrong method name capitalization
  • Confusing inclusive vs exclusive end index
3. What is the output of the following Kotlin code?
val data = " apple, banana , cherry "
val fruits = data.trim().split(",")
println(fruits[1].trim())
medium
A. ananab
B. banana
C. anana
D. banan

Solution

  1. Step 1: Apply trim() on the original string

    Calling trim() removes spaces at start and end, so string becomes "apple, banana , cherry".
  2. Step 2: Split by comma and trim the second element

    Splitting by "," gives ["apple", " banana ", " cherry"]. Then trimming the second element " banana " removes spaces, resulting in "banana".
  3. Final Answer:

    banana -> Option B
  4. Quick Check:

    trim() cleans spaces after split [OK]
Hint: Trim after split to remove spaces around parts [OK]
Common Mistakes:
  • Not trimming after split, leaving spaces
  • Assuming split trims automatically
  • Confusing index positions in list
4. Find the error in this Kotlin code snippet:
val sentence = "Hello World"
val part = sentence.substring(6, 5)
println(part)
medium
A. substring end index is less than start index causing error
B. substring method requires only one argument
C. substring indexes are inclusive, so 6 to 5 is valid
D. No error, output is "World"

Solution

  1. Step 1: Check substring parameters

    substring(startIndex, endIndex) requires startIndex ≤ endIndex. Here, startIndex=6 and endIndex=5, which is invalid.
  2. Step 2: Understand Kotlin substring behavior

    This causes an exception because the end index is less than the start index.
  3. Final Answer:

    substring end index is less than start index causing error -> Option A
  4. Quick Check:

    substring end must be ≥ start [OK]
Hint: End index must be >= start index in substring [OK]
Common Mistakes:
  • Assuming substring indexes are inclusive
  • Using end index less than start index
  • Thinking substring accepts one argument only
5. Given a string input = " red, green , blue , yellow ", write Kotlin code to create a list of trimmed color names without spaces. Which code snippet correctly achieves this?
hard
A. input.split(",").map { it.trim() }
B. input.trim().split(",")
C. input.split(",").trim()
D. input.trim().map { it.split(",") }

Solution

  1. Step 1: Split the string by commas

    Using split(",") breaks the string into parts including spaces.
  2. Step 2: Trim spaces from each part

    Using map { it.trim() } removes spaces from each color name, producing a clean list.
  3. Step 3: Evaluate other options

    input.trim().split(",") trims only the ends before splitting, so inner spaces remain. input.split(",").trim() tries to trim a list, which is invalid. input.trim().map { it.split(",") } trims the whole string then maps incorrectly.
  4. Final Answer:

    input.split(",").map { it.trim() } -> Option A
  5. Quick Check:

    Split then trim each part for clean list [OK]
Hint: Split first, then trim each piece with map [OK]
Common Mistakes:
  • Trimming before split only removes outer spaces
  • Trying to trim a list directly
  • Incorrect chaining of methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard