Back to Blog

Kotlin: Capitalize first letter of a string

Sandy LaneSandy Lane

Video: Kotlin: Capitalize first letter of a string by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Capitalize First Letter of a String

In Kotlin, capitalizing the first letter of a string is a common task that can be done easily using built-in functions. This snippet demonstrates how to transform a string so that only its first character is uppercase while the rest remain unchanged or lowercase as needed.

Code

fun capitalizeFirstLetter(input: String): String {
  if (input.isEmpty()) return input
  // Take first character, convert to uppercase, then append the rest of the string
  return input[0].uppercaseChar() + input.substring(1)
}

fun main() {
  val original = "kotlin"
  val capitalized = capitalizeFirstLetter(original)
  println(capitalized)  // Output: Kotlin
}

Key Points

  • Use the `uppercaseChar()` function to convert a single character to uppercase.
  • Concatenate the uppercase first character with the rest of the string using `substring(1)`.
  • Always check for empty strings to avoid errors when accessing characters by index.
  • This approach preserves the remainder of the string as-is, allowing for custom casing if needed.