String methods help you change or get parts of text easily. They make working with words and sentences simple.
String methods (substring, split, trim) in 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.
val text = "Hello Kotlin" val part = text.substring(0, 5) // "Hello"
val text = "apple,banana,orange" val fruits = text.split(",") // ["apple", "banana", "orange"]
val text = " hello " val cleanText = text.trim() // "hello"
val emptyText = "" val result = emptyText.trim() // ""
This program shows how to trim spaces, get a substring, and split a sentence into words.
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) }
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.
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
trim() method do when called on a string?Solution
Step 1: Understand the purpose of
Thetrim()trim()method removes whitespace characters from the beginning and end of a string.Step 2: Compare with other string methods
Unlikesplit()orsubstring(),trim()does not split or extract parts but cleans spaces around the string.Final Answer:
Removes spaces from the start and end of the string -> Option DQuick Check:
trim() removes outer spaces [OK]
- Thinking trim() splits the string
- Confusing trim() with substring()
- Assuming trim() changes case
text?Solution
Step 1: Recall Kotlin substring syntax
The correct method call issubstring(startIndex, endIndex)where endIndex is exclusive.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.Final Answer:
text.substring(2, 5) -> Option CQuick Check:
substring(start, end) uses exclusive end [OK]
- Using range syntax inside substring
- Wrong method name capitalization
- Confusing inclusive vs exclusive end index
val data = " apple, banana , cherry "
val fruits = data.trim().split(",")
println(fruits[1].trim())Solution
Step 1: Apply trim() on the original string
Callingtrim()removes spaces at start and end, so string becomes "apple, banana , cherry".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".Final Answer:
banana -> Option BQuick Check:
trim() cleans spaces after split [OK]
- Not trimming after split, leaving spaces
- Assuming split trims automatically
- Confusing index positions in list
val sentence = "Hello World" val part = sentence.substring(6, 5) println(part)
Solution
Step 1: Check substring parameters
substring(startIndex, endIndex) requires startIndex ≤ endIndex. Here, startIndex=6 and endIndex=5, which is invalid.Step 2: Understand Kotlin substring behavior
This causes an exception because the end index is less than the start index.Final Answer:
substring end index is less than start index causing error -> Option AQuick Check:
substring end must be ≥ start [OK]
- Assuming substring indexes are inclusive
- Using end index less than start index
- Thinking substring accepts one argument only
input = " red, green , blue , yellow ", write Kotlin code to create a list of trimmed color names without spaces. Which code snippet correctly achieves this?Solution
Step 1: Split the string by commas
Usingsplit(",")breaks the string into parts including spaces.Step 2: Trim spaces from each part
Usingmap { it.trim() }removes spaces from each color name, producing a clean list.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.Final Answer:
input.split(",").map { it.trim() } -> Option AQuick Check:
Split then trim each part for clean list [OK]
- Trimming before split only removes outer spaces
- Trying to trim a list directly
- Incorrect chaining of methods
Ready to prove it?
Pass the test and this pattern moves unknown
