Labs ICT
Pro Login

String Functions

Kotlin strings come packed with useful built-in functions. Here are the ones you'll reach for most often.

length

Find out how many characters a string has.


fun main() {
  val text = "Kotlin"
  println(text.length)
}
    
Try it Yourself →

uppercase and lowercase

Change the case of a string.


fun main() {
  val text = "Hello World"
  println(text.uppercase())
  println(text.lowercase())
}
    
Try it Yourself →

trim

Remove leading and trailing whitespace.


fun main() {
  val text = "  spaced out  "
  println("'${text.trim()}'")
}
    
Try it Yourself →

split

Split a string into a list using a delimiter.


fun main() {
  val csv = "apple,banana,cherry"
  val items = csv.split(",")
  println(items)
}
    
Try it Yourself →

replace

Replace occurrences of a substring with something else.


fun main() {
  val text = "I like cats"
  println(text.replace("cats", "dogs"))
}
    
Try it Yourself →

substring

Extract part of a string by specifying start and end positions.


fun main() {
  val text = "Hello Kotlin"
  println(text.substring(6, 12))
  println(text.substring(6))
}
    

substring(6, 12) gives you characters from index 6 up to (but not including) 12. With one argument, it takes everything from that index to the end.

Try it Yourself →

Chaining functions

Combine functions together for powerful one-liners.


fun main() {
  val text = "  Kotlin is Awesome!  "
  val result = text.trim().uppercase().replace("AWESOME", "FUN")
  println(result)
}
    

Each function returns a new string, so you can chain them endlessly.

Try it Yourself →