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.