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:
- Start by declaring a variable of type
Stringand assign a string value to it. For example:
val str = "hello, world!"
- 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()
- Now, the
uppercaseStrvariable 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:
- Declare a variable of type
Stringand assign a string value to it. For example:
val str = "HELLO, WORLD!"
- Call the
toLowerCase()function on the string variable and assign the result to a new variable. For example:
val lowercaseStr = str.toLowerCase()
- The
lowercaseStrvariable 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.