Challenge - 5 Problems
String Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of substring and trim
What is the output of this Kotlin code?
Kotlin
val text = " Kotlin Programming " val result = text.trim().substring(0, 6) println(result)
Attempts:
2 left
💡 Hint
Remember trim() removes spaces at the start and end before substring is applied.
✗ Incorrect
The trim() removes spaces at both ends, so the string becomes "Kotlin Programming". Then substring(0,6) takes characters from index 0 up to 6 (not including 6), which is "Kotlin".
❓ Predict Output
intermediate2:00remaining
Splitting a string and accessing elements
What will be printed by this Kotlin code?
Kotlin
val data = "apple,banana, cherry, date" val fruits = data.split(",") println(fruits[2].trim())
Attempts:
2 left
💡 Hint
Check how split works and remember to trim spaces after splitting.
✗ Incorrect
Splitting by comma creates a list: ["apple", "banana", " cherry", " date"]. The element at index 2 is " cherry" with a space. After trim(), it becomes "cherry".
🔧 Debug
advanced2:00remaining
Identify the error in substring usage
What error will this Kotlin code produce?
Kotlin
val s = "Hello" val sub = s.substring(3, 2) println(sub)
Attempts:
2 left
💡 Hint
Check the order of start and end indices in substring.
✗ Incorrect
substring(startIndex, endIndex) requires startIndex <= endIndex. Here startIndex=3 and endIndex=2, which is invalid and throws StringIndexOutOfBoundsException.
❓ Predict Output
advanced2:00remaining
Count words after splitting and trimming
What is the output of this Kotlin code?
Kotlin
val sentence = " Kotlin is fun " val words = sentence.trim().split(" ").filter { it.isNotEmpty() } println(words.size)
Attempts:
2 left
💡 Hint
Trim removes spaces at ends, split by space, then filter removes empty strings.
✗ Incorrect
After trim(), string is "Kotlin is fun". Splitting by space gives ["Kotlin", "is", "fun"]. None are empty, so size is 3.
🧠 Conceptual
expert3:00remaining
Understanding substring and split behavior
Given the Kotlin code below, what will be the output?
Kotlin
val input = "one,two,,four," val parts = input.split(",") val sub = parts[2].substring(0, 0) println("${parts.size} ${sub.isEmpty()}")
Attempts:
2 left
💡 Hint
Check how split handles consecutive commas and trailing commas, and substring with same start and end index.
✗ Incorrect
Splitting "one,two,,four," by comma results in ["one", "two", "", "four", ""], so size is 5. substring(0,0) returns empty string, so isEmpty() is true.