How to convert a string to title case in Kotlin

1 Answer

0 votes
fun String.toTitleCase(): String {
    return this.split(" ").joinToString(" ") { it.replaceFirstChar { char -> char.uppercase() } }
}

fun main() {
    val str = "In the beginning there was nothing, which exploded."
    
    val titleCaseString = str.toTitleCase()
    
    println(titleCaseString) 
}

   
      
/*
run:

In The Beginning There Was Nothing, Which Exploded.
  
*/

 



answered Apr 15, 2025 by avibootz
...