Skip to main content

How to convert a string to uppercase or lowercase in Kotlin

How to convert a string to uppercase or lowercase in Kotlin.

Here's a step-by-step tutorial on how to convert a string to uppercase or lowercase in Kotlin.

Convert String to Uppercase

To convert a string to uppercase in Kotlin, you can use the toUpperCase() function. Here's how you can do it:

  1. Start by declaring a variable of type String and assign a string value to it. For example:
val str = "hello, world!"
  1. To convert the string to uppercase, call the toUpperCase() function on the string variable and assign the result to a new variable. For example:
val uppercaseStr = str.toUpperCase()
  1. Now, the uppercaseStr variable will contain the uppercase version of the original string. You can print it to the console or use it as needed. For example:
println(uppercaseStr) // Output: HELLO, WORLD!

Here's the complete code:

val str = "hello, world!"
val uppercaseStr = str.toUpperCase()
println(uppercaseStr) // Output: HELLO, WORLD!

Convert String to Lowercase

To convert a string to lowercase in Kotlin, you can use the toLowerCase() function. Follow these steps:

  1. Declare a variable of type String and assign a string value to it. For example:
val str = "HELLO, WORLD!"
  1. Call the toLowerCase() function on the string variable and assign the result to a new variable. For example:
val lowercaseStr = str.toLowerCase()
  1. The lowercaseStr variable will now contain the lowercase version of the original string. You can print it to the console or use it as needed. For example:
println(lowercaseStr) // Output: hello, world!

Here's the complete code:

val str = "HELLO, WORLD!"
val lowercaseStr = str.toLowerCase()
println(lowercaseStr) // Output: hello, world!

That's it! You now know how to convert a string to uppercase or lowercase in Kotlin using the toUpperCase() and toLowerCase() functions.